我想使用viewpager在按鈕點擊時Toast一個消息,也想了解更多關於如何訪問viewpager中的視圖的信息。用的以下的信息,沒什麼反應。
public class MyPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return 3;
}
@Override
public Object instantiateItem(final View collection, final int position) {
v = new View(collection.getContext());
LayoutInflater inflater =
(LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.cate1;
v = inflater.inflate(R.layout.cate1, null, false);
add1 = (Button) v.findViewById(R.id.btnAdd);
add1.setOnClickListener( new OnClickListener() {
public void onClick(View m) {
Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show();
}
});
break;
case 1:
resId = R.layout.cate2;
break;
case 2:
resId = R.layout.cate3;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(final View arg0, final int arg1, final Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(final View arg0, final Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
@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
}
}
然後用下面的代碼實現button onclick方法,也不對。
v = inflater.inflate(R.layout.cate1, null, false);
add1 = (Button) v.findViewById(R.id.btnAdd);
add1.setOnClickListener( new OnClickListener() {
public void onClick(View m) {
Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show();
}
});
add1.setOnClickListener 不能執行,也沒有報錯。總之,想要實現的button action 沒有執行。是什麼問題呢?
把代碼中的
((ViewPager) collection).addView(view, 0);
return view;
改成
((ViewPager) collection).addView(v, 0);
return v;