我想實現 ViewPager 來把倆個view結合在一個activity中,但是當我在inflated views裡使用findViewById來訪問item時, 現在遇到的錯誤是NullPointerException。
自定義的 page adapter:
public class CustomPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void destroyItem(View view, int value, Object object) {
((ViewPager) view).removeView((View) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public Object instantiateItem(View collection, int position) {
LayoutInflater layoutInflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resultId = 0;
switch (position) {
case 1:
resultId = R.layout.layout2;
break;
case 0:
default:
resultId = R.layout.layout1;
break;
}
View view = layoutInflater.inflate(resultId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
}
activity 如下,我想訪問 layout1 中的 button ,但是給出 null 值。
public class PageSwiperActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpagerlayout);
Button myButton=(Button) findViewById(R.id.myButton);
}
}
viewpagerlayout.xml
<android.support.v4.view.ViewPager
android:id="@+id/viewPagerLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
layout1.xml包含一個按鈕。 請指點一二,謝謝!
你在 ViewPager 中設置 PageAdapter了嗎?如果沒有設置,然後使用按鈕刪除line,然後在activity中添加代碼:
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPagerLayout);
viewPager.setAdapter(new CustomPagerAdapter());
取代:
Button myButton = (Button) findViewById(R.id.myButton);
你可以調用 findViewById 來獲取 adapter 這個方法中的按鈕:
@Override
public Object instantiateItem(View collection, int position) {
... // your previous code
final Button myButton = (Button) findViewById(R.id.myButton);
return view;
}