Android findViewById() 在 onCreate() 中调用时返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21680927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
findViewById() returns null when I call it in onCreate()
提问by JRivera294
I'm having a problem with the findViewById on my first android app. I'm trying to call this function but always return null.
我的第一个 Android 应用程序上的 findViewById 有问题。我正在尝试调用此函数,但始终返回 null。
My app have 2 activities. In the second activity (activity_display_message) I have this code:
我的应用程序有 2 个活动。在第二个活动 (activity_display_message) 中,我有以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
//Obtener el mensaje desde el intent en MainActivity
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Buscar el textview en la vista
TextView textView = (TextView) findViewById(R.id.texto);
textView.setText(message);
}
And this is the fragment_display_message.xml
这是 fragment_display_message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.app.DisplayMessageActivity$PlaceholderFragment">
<TextView
android:id="@+id/texto"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
I don't know why it return NULL and generate a NullPointerException
when I try to do a setText()
. I'm calling the correct Id and declaring it on the XML too. And I'm calling the setContextView()
on the onCreate()
.
我不知道为什么它返回 NULL 并NullPointerException
在我尝试执行setText()
. 我正在调用正确的 Id 并在 XML 上声明它。而我打电话setContextView()
的onCreate()
。
Sorry if this question is too obvious (I think that I'm ignoring something obvious) but I'm new on android development.
对不起,如果这个问题太明显了(我认为我忽略了一些明显的东西),但我是 android 开发的新手。
EDIT: Logcat error:
编辑:Logcat 错误:
02-10 10:25:58.960 1031-1031/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 1031
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.DisplayMessageActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access0(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
??????????
?????????
Edit:
编辑:
Problem solved. Just need move the code from onCreate()
to onCreateView()
and edit the references.
问题解决了。只需要将代码从onCreate()
to移动onCreateView()
并编辑引用。
onCreate()
will be the default.
onCreate()
将是默认值。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
And the onCreateView()
on PlaceholderFragment
:
而onCreateView()
在PlaceholderFragment
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
//Obtener el mensaje desde el intent en MainActivity
Intent intent = getActivity().getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Buscar el textview en la vista
TextView textView = (TextView) rootView.findViewById(R.id.texto);
textView.setText(message);
return rootView;
}
采纳答案by laalto
Activity
findViewById()
searches the activity's view hierarchy set with setContentView()
for the given view id. The view you appear to be looking for is in a fragment and not in the activity hierarchy (yet). Fragment transactions are not immediate either so even if you add it to the container in the activity hierarchy, it is not attached there right away but only when the transaction is processed.
Activity
findViewById()
setContentView()
为给定的视图 ID搜索活动的视图层次结构。您似乎正在寻找的视图位于片段中,而不是在活动层次结构中(尚未)。片段事务也不是即时的,因此即使您将其添加到活动层次结构中的容器中,它也不会立即附加到那里,而是仅在处理事务时才附加到那里。
In theory it's possible to synchronously execute pending fragment transactions with executePendingTransactions()
. However, it's better to just move the code that touches a fragment's views in its onCreateView()
. Fragments and their hosting activities are supposed to be relatively independent of each other, so an activity accessing a fragment's internals should be avoided.
理论上,可以使用executePendingTransactions()
. 但是,最好只将接触片段视图的代码移动到onCreateView()
. Fragment 及其托管活动应该彼此相对独立,因此应避免访问 Fragment 内部的活动。
回答by Blackbelt
you are looking for texto
in the wrong place. The layout of your activity is activity_display_message
but texto
belongs to fragment_display_message.xml
你texto
在错误的地方寻找。您的活动的布局是activity_display_message
但texto
属于fragment_display_message.xml
回答by JamesC
I agree with Blackbelt. You're looking in the wrong place.
In addition I'd suggest adding id
to the layout using the "@+id/<name>"
,
this way you'll know exactly where you are in the hierarchy.
我同意黑带。你找错地方了。此外,我建议id
使用 来添加布局"@+id/<name>"
,这样您就可以确切地知道您在层次结构中的位置。