Android:findViewById返回null?

时间:2013-06-06 20:50:56

标签: java android null findviewbyid

在我的主要活动中,我正在尝试访问我在主ScrollView中的LinearLayout。我的ScrollView实现如下:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:id="@+id/graph" 
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="250dip"
         />



</ScrollView>

在我的Main活动中,我对scrollView进行了充气,​​然后尝试按如下方式访问线性布局:

LayoutInflater inflater;
    inflater = (LayoutInflater)  this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);              

    ScrollView mainLayout = (ScrollView) inflater.inflate(R.layout.scrollview,
                    null);
    LinearLayout layout = (LinearLayout) findViewById(R.id.graph);

为什么我的findViewById会在这里返回null?我一开始以为它试图在它完成膨胀之前找到它,但我已经尝试过一个while循环来等待它完成膨胀,这也无济于事。

2 个答案:

答案 0 :(得分:4)

你必须给它夸大的布局

LinearLayout layout = (LinearLayout) mainLayout.findViewById(R.id.graph);

答案 1 :(得分:0)

您可以首先仔细检查是否在inflater.inflate()中指定了错误的布局。