【问题标题】:Updating TextView in onCreate()在 onCreate() 中更新 TextView
【发布时间】:2014-07-24 13:44:08
【问题描述】:

我想更新onCreate()中的TextView,这样在出现Activity界面时应该设置文字,我试过的是:

Java 代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sem_selection);

    TextView T =(TextView)findViewById(R.id.textView1); 
    T.setText("required text"); 

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

但是当活动开始时我得到错误,只要我评论这一行:

T.setText("required text");  

应用程序运行良好,没有错误。我该怎么做?还有其他方法吗?

【问题讨论】:

  • 您的textView1 可能在PlaceholderFragment 中。将其移至onCreateView
  • 什么错误?发布您的 LogCat/Stacktrace
  • 是的,那必须在 onCreatView() 里面,解决了:)

标签: android


【解决方案1】:

您从fragment 引用TextView T,您将获得空值,因为在您的活动中,您正在使用activity_sem_selection 并从activity_sem_selection 布局获取TextView T

所以在片段的onCreateView方法中使用T

例如

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment__sem_selection, container,
                false);

        TextView T =(TextView)rootView.findViewById(R.id.textView1); 
        T.setText("required text"); 

        return rootView;
    }

注意:使用您的片段布局更改fragment__sem_selection

【讨论】:

  • 另外,最好对变量使用小写字母 - TextView t 而不是 T
  • 非常感谢#Giru bhai :) 它工作得很好,现在我无法理解我之前犯的错误,这是一个空指针异常,我是一个初学者,请详细说明,谢谢前进。
  • @ÅdəəlÅhmåd 乐于助人,别忘了接受答案。
  • 接受 :)p.s 我只是要求对我的错误进行一点解释,先生'
【解决方案2】:

删除

 if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction()
             .add(R.id.container, new PlaceholderFragment()).commit();
   }

【讨论】:

    【解决方案3】:

    检查textView1 是否存在于activity_sem_selection 布局中。否则你会得到NPE。尝试在activity_sem_selection 布局中放置一个ID 为textView1TextView。否则,您可以删除那些对 TextView T 的分配和引用,并将它们放在 fragment's onCreateView(...) 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多