最近做项目遇到Viewpager+Fragment滑动页面,要监听子页面中的按钮,在网上查了些解决办法:
办法一:
这种方法是在适配器初始化中进行监听,有人亲测通过,但是我继承FragmentPagerAdapter,未果。
@Override
public Object instantiateItem(final View view, int position) {
switch (position) {
case 0:
btnKnowledge = (Button)mListViews.get(position).findViewById(R.id.tab_knowledge);
btnKnowledge.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "XXXXXX", 1).show();
}
});
break;
default:
break;
}
((ViewPager) view).addView(mListViews.get(position), 0);
return mListViews.get(position);
}
方法二:
这个方法也是我自己用的方法,得以解决。不多说,直接上代码。
private class ShinStarterHelpPageAdapter extends FragmentPagerAdapter {
public ShinStarterHelpPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
StarterHelpPageFragment fragment = null;
if (position != 2)
fragment = new StarterHelpPageFragment();
else
fragment = new StarterHelpFirstPageFragment(selectIRM03Listener, selectIRM01Listener, selectIRM02Listener);
Bundle bundle = new Bundle();
bundle.putInt(StarterHelpPageFragment.KEY_RES_ID, resIds[position]);
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return resIds.length;
}
}
public class StarterHelpFirstPageFragment extends StarterHelpPageFragment {
private OnClickListener selectIRM03Listener = null;
private OnClickListener selectIRM02Listener = null;
private OnClickListener selectIRM01Listener = null;
public StarterHelpFirstPageFragment(OnClickListener selectIRM03Listener, OnClickListener selectIRM01Listener, OnClickListener selectIRM02Listener) {
this.selectIRM01Listener = selectIRM01Listener;
this.selectIRM02Listener = selectIRM02Listener;
this.selectIRM03Listener = selectIRM03Listener;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button again_connect = (Button) view.findViewById(R.id.again_connect);
Button histus = (Button) view.findViewById(R.id.histus);
Button st_search = (Button) view.findViewById(R.id.st_search);
again_connect.setOnClickListener(this.selectIRM01Listener);
histus.setOnClickListener(this.selectIRM02Listener);
st_search.setOnClickListener(this.selectIRM03Listener);
}
}
private OnClickListener selectIRM03Listener = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
private OnClickListener selectIRM01Listener = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
private OnClickListener selectIRM02Listener = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
这种方法就是直接将第三个页面给抽出来,单独进行监听,然后再放到Viewpager里面,本人亲测,代码通过编译,希望对大家有帮助。