[英]Android: findViewById is returning null?
在我的主要活動中,我試圖訪問主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>
在我的主要活動中,我給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循環來等待它完成充氣,但這也無濟於事。
你必須給它膨脹的布局
LinearLayout layout = (LinearLayout) mainLayout.findViewById(R.id.graph);
您可以再次檢查是否首先在inflater.inflate()中指定了錯誤的布局。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.