由于永远不会在 a 上触发 onClick 事件ViewPager
(请参阅此问题),我将onClickListener
在适配器中将 设置为项目容器。
这个想法是,当单击一个项目时,从适配器调用来自该适配器设置为的 Fragment 的方法ViewPager
。
对于一个Activity
我会传递上下文并使用这个上下文调用方法(类似于((myActivity)context).itemContainerOnClick()
)。
但是我该如何处理片段?将 Fragment 作为参数传递给适配器的构造函数时,我会遇到任何问题吗?
谢谢
分段
public class MyFragment extends Fragment {
ViewPager mViewPager;
int mPosition = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.my_fragment_container, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new MyAdapter(getActivity(), myObjectArray);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mPosition = position;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageScrollStateChanged(int state) {}
});
mViewPager.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// I want to start some activity, passing mPosition
// but this is never called
}
});
return view;
}
// Alternative to mViewPager.setOnClickListener, called from the adapter
public void onViewPagerClick()
{
// start some activity, passing mPosition
}
}
页面适配器
class MyAdapter extends PagerAdapter {
private MyObject[] mItemArray;
private Context mContext;
public SejoursWidgetAdapter(Context context, MyObject[] itemArray) {
mContext = context;
mItemArray = itemArray;
}
@Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item, null);
// Add click listener here because setting it directly on the ViewPager does not work (onClick not triggered)
row.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// How can I call MyFragment's onViewPagerClick() ?
}
});
((ViewPager) collection).addView(row);
return row;
}
/* More stuff */
}