【问题标题】:how can i change textview text of fragment from activity我如何从活动中更改片段的文本视图文本
【发布时间】:2014-08-31 18:01:34
【问题描述】:

我在主要活动中动态添加了片段(从 secfrag.xml 膨胀)。我的主要活动中有两个按钮。一个用于添加片段,另一个用于更改我的片段的文本。我已成功将片段添加到我的活动中,但我无法更改片段的 textview 文本。我怎样才能做到这一点。

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");
        }
    });

}

【问题讨论】:

  • 如果用户点击addFragment两次,从而添加了两个片段,点击changeFragText应该更改哪些文本?

标签: java android android-activity fragment


【解决方案1】:

您应该在片段内创建一个方法来更改文本。

例如

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");
}

然后在你的 onClickListener 中你可以调用那个方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多