小编Vip*_*pul的帖子

如果没有调用setcontentview(),为什么findViewById()返回null?

我是android的新手.

这是我的xml文件 -

<LinearLayout 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"
    tools:context=".MainActivity" 
    android:id="@+id/linearlayout"
    android:orientation="vertical">

    <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/hello_world"
     android:id="@+id/textview" />

  </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

和非常基本的代码 -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View view=getLayoutInflater().inflate(R.layout.activity_main,null);

            //setContentView(view);

            LinearLayout ly = (LinearLayout)findViewById(R.id.linearlayout);

            Log.i("System.out ","linear layout = " + view);

            Log.i("System.out ","linear layout = " + ly);
    }
Run Code Online (Sandbox Code Playgroud)

输出:

05-10 11:44:15.996: I/System.out(6494): linear layout = android.widget.LinearLayout@41e34db8
05-10 11:44:15.996: I/System.out(6494): linear layout = null
Run Code Online (Sandbox Code Playgroud)

findViewById()正在返回null?为什么?

如果我取消注释setContentView(view)并再次运行..

输出:

05-10 11:50:12.781: I/System.out(7791): linear layout = android.widget.LinearLayout@41e0d6c8
05-10 11:50:12.781: I/System.out(7791): …
Run Code Online (Sandbox Code Playgroud)

null android inflate findviewbyid

1
推荐指数
1
解决办法
2578
查看次数

标签 统计

android ×1

findviewbyid ×1

inflate ×1

null ×1