2013-05-10 99 views
1

我是新的蜜蜂到android。为什么如果没有调用setcontentview(),findViewById()返回null?

这里是我的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> 

和非常基本的代码 -

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

输出:

05-10 11:44:15.996: I/System.out(6494): linear layout = [email protected] 
05-10 11:44:15.996: I/System.out(6494): linear layout = null 

findViewById()被返回null?为什么?

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

输出:

05-10 11:50:12.781: I/System.out(7791): linear layout = [email protected] 
05-10 11:50:12.781: I/System.out(7791): linear layout = [email protected] 

什么额外的不setContentView()是干什么的?

回答

6
public void setContentView (View view) 

将活动内容设置为显式视图。该视图直接放置在活动的视图层次结构中。

setContentView(View view)是activity类的一个方法。当创建活动时,您需要将内容设置为您的活动。

onCreate(Bundle)是您初始化您的活动的地方。最重要的是,在这里,您通常会使用定义UI的布局资源调用setContentView(view),并使用findViewById(int)来检索该UI中需要以编程方式进行交互的小部件。

您的onCreate()实现应定义用户界面,并可能实例化一些类作用域变量。

像文本视图的每个资源,在布局文件添加时在R.java文件中的条目是自动

对于activity_main在R.java

 public static final class layout { 
     public static final int activity_main=0x7f030000; 
     } 
将有一个条目可绘

在你的情况下,你膨胀的布局,但没有设置内容的活动。

您需要将内容设置为您的活动,然后使用findViewById(..)查找ID。

如果不是,您将得到NullPointerException。

+0

谢谢。那么,这是否意味着如果一个视图与某个活动没有关联,则findViewById()将始终返回null。 – Vipul 2013-05-10 07:38:14

+0

@ user2368689是的,你也可以找到你设置内容的布局视图的id为活动 – Raghunandan 2013-05-10 07:41:09

+0

@Raghunandant,谢谢! – Vipul 2013-05-10 07:53:34