【问题标题】:findViewById() returns null when I call it in onCreate()当我在 onCreate() 中调用 findViewById() 时返回 null
【发布时间】:2014-02-10 15:17:16
【问题描述】:

我的第一个 Android 应用程序的 findViewById 出现问题。我正在尝试调用此函数,但总是返回 null。

我的应用有 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);
}

这是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" />

我不知道为什么当我尝试执行setText() 时它返回NULL 并生成NullPointerException。我正在调用正确的 Id 并在 XML 上声明它。我在onCreate() 上拨打setContextView()

对不起,如果这个问题太明显了(我认为我忽略了一些明显的东西),但我是 android 开发的新手。

编辑: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.access$800(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)

          

编辑:

问题解决了。只需将代码从onCreate() 移动到onCreateView() 并编辑引用即可。

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

还有PlaceholderFragment上的onCreateView()

        @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;
    }

【问题讨论】:

  • 你能发布堆栈跟踪吗?
  • 输入您的 logcat 详细信息
  • 请将解决方案发布为答案并将其标记为正确答案。否则,其他人很难找出真正解决了您的问题的方法。不应在 OP 中发布解决方案。

标签: android


【解决方案1】:

Activity findViewById() 在使用setContentView() 设置的活动视图层次结构中搜索给定的视图ID。您似乎正在寻找的视图位于片段中,而不是在活动层次结构中(尚未)。片段事务也不是即时的,因此即使您将其添加到活动层次结构中的容器中,它也不会立即附加到那里,而是仅在处理事务时才附加。

理论上,可以使用executePendingTransactions() 同步执行待处理的片段事务。但是,最好只在其onCreateView() 中移动触及片段视图的代码。片段和它们的宿主活动应该是相对独立的,所以应该避免访问片段内部的活动。

【讨论】:

  • 它永远不会出现在 Activity 的视图层次结构中。它将属于 Fragment 的。此外,如果片段将附加到 Activity,findViewById 返回 null
  • 我一直在怀疑,但我该如何解决呢?
  • @blackbelt 可见片段存在于活动视图层次结构中。片段视图层次结构实际上是活动视图树中的子树。
  • 所以 findViewById 不会返回 null?
  • @blackbelt 片段事务执行后没有。
【解决方案2】:

您在错误的地方寻找texto。您的活动布局是activity_display_message,但texto 属于fragment_display_message.xml

【讨论】:

  • 我正在使用 android studio,当我使用它在布局 2 文件、activity_display_message.xml 和 fragment_display_message.xml 上创建的 IDE 创建一个活动时,当我将对象添加到片段活动并将 setContentView 调用到 activity_display_message 我猜它重定向到 fragment_display_message
【解决方案3】:

我同意黑带。你找错地方了。 此外,我建议使用"@+id/&lt;name&gt;"id 添加到布局中, 这样你就可以准确地知道你在层次结构中的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2011-03-16
    • 1970-01-01
    相关资源
    最近更新 更多