我在ViewPager中有兩個頁面。在這兩個頁面中,我有按鈕,我必須對它們進行操作。點擊監聽器的按鈕對第二頁它不適用於第一頁。 這裏是我試圖點擊監聽器在View尋呼機中不工作
public class MainActivity extends Activity {
int noofsize = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,
noofsize);
ViewPager myPager = (ViewPager) findViewById(R.id.reviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
活動和適配器類和適配器類是如下
public class ViewPagerAdapter extends PagerAdapter implements OnClickListener {
int size;
Activity act;
View layout;
TextView pagenumber;
Button click;
public ViewPagerAdapter(MainActivity mainActivity, int noofsize) {
// TODO Auto-generated constructor stub
size = noofsize;
act = mainActivity;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return size;
}
@Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.pages, null);
pagenumber = (TextView) layout.findViewById(R.id.pagenumber);
pagenumber.setText("Now your in Page"+position);
click = (Button) layout.findViewById(R.id.click);
click.setOnClickListener(this);
((ViewPager) container).addView(layout, 0);
return layout;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == click) {
Toast.makeText(act, "click event called", Toast.LENGTH_SHORT)
.show();
}
}
}
爲什麼在適配器中使用onclick()?它應該在碎片或活動中 –