简体   繁体   English

我如何从活动中更改片段的textview文本

[英]how can i change textview text of fragment from activity

i have dynamically added fragment(which is inflated from secfrag.xml) in main activity. 我在主要活动中动态添加了片段(从secfrag.xml夸大)。 there are two buttons in my main activity. 我的主要活动中有两个按钮。 one for adding fragment and the other is for changing text of my fragment. 一个用于添加片段,另一个用于更改片段的文本。 i have successfully added fragment to my activity but i can not change the textview text of my fragment. 我已成功将片段添加到我的活动中,但是我无法更改片段的textview文本。 how can i do that. 我怎样才能做到这一点。

public class MyActivity extends ActionBarActivity {
   Button addFragment;
   Button changeFragText;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    addFragment = (Button) findViewById(R.id.mybtn);
    changeFragText = (Button) findViewById(R.id.mybtn2);



    addFragment.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
                Secfragjava secfragjava = new Secfragjava();
                getFragmentManager().beginTransaction().add(R.id.mainholder, secfragjava).commit();

            }


        });

    changeFragText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            //how can i have the fragment and change its textview
            TextView frv=(TextView) getFragmentManager().findFragmentById(R.id.container).getView().findViewById(R.id.mysecText);
            frv.setText("raton");
        }
    });

}

You should create a method inside of your fragment for changing the text. 您应该在片段内部创建一个用于更改文本的方法。

eg 例如

public void changeText(){
    //this textview should be bound in the fragment onCreate as a member variable
    TextView frv=(TextView) getView().findViewById(R.id.mysecText);
    frv.setText("raton");
}

Then in your onClickListener you can just call that method: 然后,您可以在onClickListener中调用该方法:

((Secfragjava)getFragmentManager().findFragmentById(R.id.container)).changeText();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM