![](/img/trans.png)
[英]Android ViewPager findViewById(R.id.viewPager) always returns null
[英]Android ViewPager findViewById not working - Always returning null
public class HSPTabletTestActivity extends Activity {
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 2;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.lighttab;
break;
case 1:
resId = R.layout.securitytab;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
@Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
@Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
}
我在那里有這個代碼^^ ...幾乎直接來自http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/ ...我是在android開發的世界中還是相當新的:/
現在我正在嘗試訪問微調器控件和“頁面”內的一些按鈕。 但findViewById一直返回null!
我記得有些布局在代碼中並不存在,並且必須首先進行膨脹,這在instantiateItem()函數中發生。 而且很明顯它會進入“視圖”變量。 但是當我調用view.findViewById(R.id.light1_off)時;
順便說一句,這是一個按鈕,它總是返回ZERO! 我甚至確定只在實際加載頁面時調用它。 但無論我做了什么,它總是保持返回null並且我得到一個令人討厭的nullpointer異常。
有人可以幫幫我嗎? 我幾乎沒有任何想法,谷歌沒有任何幫助,已經在大約10個不同的搜索條件的第5頁。
經過多次挫折並在這個問題上拉扯我的頭發,我已經解決了! 至少對於我來說。 假設您像我一樣使用了tutsplus教程,那么您的屏幕就有單獨的XML文件。 現在,我假設這些布局XML包含其中的布局(即LinearLayout,RelativeLayout等)。 現在,這些布局包含您的按鈕和其他小部件。 你需要做的是能夠findViewById,在instatiateItem方法的實際switch語句中,以這種方式初始化你的按鈕:
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.lighttab;
View view = inflater.inflate(resId, null);
RelativeLayout layout=(RelativeLayout)view.findViewById(R.id.relLayout);
Button button=(Button)layout.findViewById(R.id.button);
((ViewPager) collection).addView(view, 0);
return view;
case 1:
resId = R.layout.securitytab;
...
...
return view;
}
}
所以......首先你必須給視圖充氣,然后通過強制轉換布局類型(RelativeLayout)並調用.findViewById(資源id)來初始化視圖中保存的布局。 然后,通過執行相同操作來初始化您正在尋找的實際窗口小部件,但是轉換窗口小部件類型(Button)並調用.findViewById(資源ID)。
這對我有用,所以我希望這能為你節省一些麻煩! 永遠讓我弄清楚。
你可以在findViewById之前添加setContentView(R.layout.youlayout)來避免所有這些臟工作
只是猜測你沒有顯示膨脹的xml。 你使用+ @ id。 如果不試一試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.