Why findViewById() is returning null if setcontentview() is not called?

女生的网名这么多〃 提交于 2020-01-09 11:52:29

问题


I am new-bee to android.

Here is my xml file -

<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>

and Very basic code -

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

Output:

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

findViewById() is returning null? Why?

If I uncomment setContentView(view) and run again ..

Output:

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): linear layout = android.widget.LinearLayout@41e0d6c8

What extra does setContentView() is doing?


回答1:


   public void setContentView (View view)

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy.

setContentView (View view) is a method of activity class. When activity is created you need to set the content to your activity.

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(view) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

Your implementation of onCreate() should define the user interface and possibly instantiate some class-scope variables.

Every resource like text view ,drawables when added in layout files will have an entry in R.java files The entry is automatic

Example

For activity_main in R.java

        public static final class layout {
        public static final int activity_main=0x7f030000;
        }

In your case your inflating the layout but not setting the content to the activity.

You need to set the content to your activity and then find the ids using findViewById(..).

If not you will get NullPointerException.



来源:https://stackoverflow.com/questions/16476424/why-findviewbyid-is-returning-null-if-setcontentview-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!