我正在創建一個自定義/擴展的LinearLayout,我將其添加到ViewAnimator顯然是爲了很酷的效果。android擴展LinearLayout,添加XML與LayoutInflater,findViewById爲空
所以我的主要活動有一個ViewAnimator,我創建了這個NavigationView的一個實例,我一直在努力並將它作爲子視圖添加到ViewAnimator中。 NavigationView本身使用LayoutInflater來獲取我製作的界面的xml並將其附加到自己。
然後我嘗試找到這個微調,我知道有正確的ID,它總是返回null。如果我使用這個XML作爲Activity的主要內容視圖,那麼找到Spinner就沒有問題。
這裏是我的代碼:
public class NavigationView extends LinearLayout {
public NavigationView(Context context) {
super(context);
addView(context);
}
public NavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
addView(context);
}
public void addView(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.nav, this, true);
Spinner spinner = (Spinner) findViewById(R.id.nav_spinner);
if(spinner == null) Log.v("spinner", "null");
}
}
所以我總是看到 「微調」 作爲logcat的 「空」。
我看到我創建的界面添加到屏幕上,但它驅使我堅持爲什麼它不會通過id找到這個對象。
難道是因爲它誇大了它不能正確分配ID嗎?
我試過,但它也返回null。所以做以下事情:活動a =(活動)上下文; Spinner spinner =(Spinner)a.findViewById(R.id.nav_spinner); – Paul 2011-03-08 23:03:39
嗯,在這種情況下,嘗試將nav_spinner重命名爲不同的id名稱,我似乎記得在xml佈局中爲小部件設置了下劃線會導致Android有趣的效果....一旦您將它重命名爲id沒有下劃線嘗試我在答案中提到的內容。 – 2011-03-08 23:06:55
我拿出下劃線但沒有成功。 – Paul 2011-03-08 23:12:04