如何在viewpager 中的主Activity中得到其他頁面的Button
public class MainActivity extends Activity {
private LinearLayout indexLayout;
private ImageView[] indexViews=new ImageView[4];
private ViewPager vp;
private View[] views=new View[4];
private Button btn3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initIndex();
vp=(ViewPager)findViewById(R.id.viewPager);
views[0]=getLayoutInflater().inflate(R.layout.page1, null);
views[1]=getLayoutInflater().inflate(R.layout.page2, null);
views[2]=getLayoutInflater().inflate(R.layout.page3, null);
views[3]=getLayoutInflater().inflate(R.layout.page4, null);
ViewPagerAdapter adapter=new ViewPagerAdapter();
vp.setAdapter(adapter);
ViewPager.OnPageChangeListener listener=new ViewPager.OnPageChangeListener() {
public void onPageSelected(int arg0) {
System.out.println("onPageSelected");
for(ImageView iv:indexViews){
iv.setBackgroundResource(R.drawable.present);
}
indexViews[arg0].setBackgroundResource(R.drawable.santa);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
vp.setOnPageChangeListener(listener);
}
class ViewPagerAdapter extends PagerAdapter{
public int getCount() {
return views.length;
}
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(views[position]);
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(views[position]);
return views[position];
}
}
private void initIndex() {
indexLayout=(LinearLayout)findViewById(R.id.indexLayout);
for(int i=0;i<4;++i){
indexViews[i]=new ImageView(this);
}
indexViews[0].setBackgroundResource(R.drawable.santa);
indexViews[0].setLayoutParams(new LayoutParams(25,25));
for(int i=1;i<=3;++i){
indexViews[i].setBackgroundResource(R.drawable.present);
indexViews[i].setLayoutParams(new LayoutParams(25,25));//width,height
}
for(int i=0;i<4;++i){
indexLayout.addView(indexViews[i]);
}
}
}
第一我想明確以下你的提問:
你的提問的意思應該是:在含有viewpager的activity中,如何獲取不同pager的button實例。
如果你的問題是這樣的話,我覺得有下面的解決辦法,你可以嘗試以下。
比如說,你想獲取第一個pager裡面的buton,你可以通過Button button=view[0].findViewById(R.id.buttonId);來獲取Button.