在Fragment中更改TextView

8
我跟随这个人的教程学习如何制作ActionBar,链接在此:tutorial。现在假设我想要改变其中一个片段内部的TextView。那么我就在StartActivity.java文件的onCreate方法下添加了以下代码:
TextView textview = (TextView) findViewById(R.id.textView1);
textview.setText("HI!");

当我启动应用时,它会崩溃。有人能指导我吗?

希望有人花时间看一下这个教程,因为他的布局基本上和我的一样。谢谢。


2
什么是崩溃?展示Logcat日志。 - Renjith
@Mnemone请发布抛出异常的代码部分。 - TheFlash
请指出在代码中使用setText()的位置。 - Sam
4个回答

13

如果您想更改组件,我建议在片段内创建一个像这样的方法:

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;

    public class DetailFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.details, container, false);
            return view;
        }


        public void setText(String text){
            TextView textView = (TextView) getView().findViewById(R.id.detailsText);
            textView.setText(text);
        }

    }

3
getView() 总是为空。 - Randy
我该如何从“MainActivity”访问它? - Si8

5

您可以尝试用getActivity()替换getView()吗?

public void setText(String text){
        TextView textView = (TextView) getActivity().findViewById(R.id.detailsText);
        textView.setText(text);
    }

4
我在这里Stack Overflow找到了答案。它使用了inflater来实现(对我很有效)。

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inf = inflater.inflate(R.layout.fragment_place, container, false);
        TextView tv = (TextView) inf.findViewById(R.id.textview);
        tv.setText("New text");
        return inf;
    }
}

1
在您的主活动中,像这样实例化您的碎片类。
    public class MainActivity extends AppCompatActivity {
          private YourFragmentClass your_fragment;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);

              your_fragment = new YourFragmentClass("pass the string value here")
    }
}

在您的片段类中,您可以像这样获取字符串并使用setText使其显示:

    public class YourFragmentclass extends Fragment {

     private String your_text;


      public YourFragmentClass(String your_text) {
       this.your_text = your_text;
      }


      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = (View)inflater.inflate(R.layout.fragment_layout, container, false);

       //set the text of your text view
        TextView textView = (TextView) view.findViewById(R.id.text_view_id);
        textView.setText(your_text);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接