OnItemClickListener doesnt get called when using ViewPager in a Listview

青春壹個敷衍的年華 提交于 2019-12-08 06:17:14

问题


I have a ViewPager in a ListView. Everything works fine ( vertical scroll in list view / horizontal scroll in ViewPager). But I am having problems catching on click event on the listview items (the viewpager fills the listview item).

So far I tried

  • set the list view to clickable

  • extended Viewpager and added a gesture detector which detects horizontal scroll and sets requestDisallowInterceptTouchEvent(false) if the gesture is not horizontal scroll

  • set setOnItemClickListener for my list view

problem: setOnItemClickListener doesn't get called

I was also trying to add the onclick listner dirrectly to the viewPager but the listner was not called aswell

Basicly I am looking for a sollution which I can detect a click on the listview item or the page viewer and launch a intent.

P.S Any links on how android handles touch events on views will be also appreciated


回答1:


You're close, but instead of setting an onClickListener on the ViewPager itself, you must set an onClickListener to the view in the ViewPager's PagerAdapter (which you must extend).

In your ListView's getView(), where you instantiate the ViewPager, set an adapter to your PagerAdapter (here called "ExtendedPagerAdapter):

ViewPager pager = (ViewPager) container.findViewById(R.id.pager);
ExtendedPagerAdapter adapter = new ExtendedPagerAdapter(context, list);
pager.setAdapter(adapter);

Then, in your ExtendedPagerAdapter class, you override (among other things) instantiateItem(ViewGroup, int).

@Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater)
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View theView = list.get(position).getView(inflater);

    theView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //perform action
        }
    });

    container.addView(theView, 0);
    return theView;
}


来源:https://stackoverflow.com/questions/22515158/onitemclicklistener-doesnt-get-called-when-using-viewpager-in-a-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!