小编JRi*_*294的帖子

当我在onCreate()中调用它时,findViewById()返回null

我的第一个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);
}
Run Code Online (Sandbox Code Playgroud)

这是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" />
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它会返回NULL并NullPointerException在我尝试执行时生成一个setText().我正在调用正确的Id并在XML上声明它.而我正打电话setContextView()onCreate().

对不起,如果这个问题太明显了(我认为我忽略了一些明显的事情),但我是Android开发的新手.

编辑:Logcat错误:

02-10 10:25:58.960    1031-1031/com.example.app …
Run Code Online (Sandbox Code Playgroud)

android

22
推荐指数
1
解决办法
3万
查看次数

标签 统计

android ×1