Android 从“获取文本视图对象”;onCreate";活动';s法
我在尝试从活动中通过onCreate方法中的id检索TextView对象时遇到问题 我的活动的xml片段TextView部分:Android 从“获取文本视图对象”;onCreate";活动';s法,android,Android,我在尝试从活动中通过onCreate方法中的id检索TextView对象时遇到问题 我的活动的xml片段TextView部分: <TextView android:id="@+id/message_display_field" android:layout_width="fill_parent" android:layout_height="wrap_content" /> TextView tv=(TextView)findViewById(R.id.me
<TextView
android:id="@+id/message_display_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
TextView tv=(TextView)findViewById(R.id.message\u display\u字段)代码>不返回textView,我希望它返回,但返回null
最后,正如我们所料,这会抛出一个NullPointerException
如果不是这样的话,我如何检索我的TextView对象呢<代码>:(
注:
- 在我按下Run按钮通过emulator启动应用程序之前,没有警告或错误
- 在运行时触发空指针
我将感谢您的帮助,提前谢谢!实际上,如果您的文本视图包含片段xml,您需要做的是: 1-转到class fragment override onCreateView方法,从中可以获得片段内部的所有视图,如下所示
TextView foo;as //globle var
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
foo = rootView.findViewById(R.id.message_display_field);
return rootView;
}
现在你快乐了我希望这能有所帮助这是你的
活动中的文本视图
显示消息
XML文件吗?你的文本视图在片段中吗?@NoXSaeeD@user184994是的,它是:/
这实际上是错误的。onCreate在onCreateView之前调用onCreate。你可能是想在创建的视图上编写activitycreate或更好的,是吗?是的,你说得对我的意思是onCreateView,所以这里是如何从片段中获得视图的答案编辑完成,如果我要得到最好的答案,因为没有其他人会对我投票回答,谢谢。
TextView foo;as //globle var
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
foo = rootView.findViewById(R.id.message_display_field);
return rootView;
}