40

我是 Viewpager 的新手,在从谷歌阅读http://developer.android.com/reference/android/support/v4/view/ViewPager.html之后,我似乎找不到任何与viewPager.setOnItemClickListener(new OnItemClickListener() {我们是否有其他相关的内容选项作为单击的项目?

测试

viewPager.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent i = new Intent(MainActivity.this, SingleItemView.class);
                i.putExtra("flag", flag);
                i.putExtra("position", position);
                startActivity(i);
            }

        });

错误:未为 ViewPager 类型定义方法 setOnItemClickListener(new AdapterView.OnItemClickListener(){})

4

7 回答 7

91

ViewPager 没有 OnItemClick 回调方法。如果您想在每个页面上单击事件,则必须将侦听器构建到适配器内的页面内容中。

像这样的东西:

@Override
public Object instantiateItem(View collection, final int pos) { //have to make final so we can see it inside of onClick()
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    View page = inflater.inflate(R.layout.YOUR_PAGE, null);

    page.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            //this will log the page number that was click
            Log.i("TAG", "This page was clicked: " + pos);
        }
    });


    ((ViewPager) collection).addView(page, 0);
    return page;
}

您究竟需要什么将取决于您在instantiateItem()其中还没有发布的其他内容,因此我无法给您更具体的答案。

于 2013-05-03T03:19:28.530 回答
40

我实现了自定义ViewPager

public class ClickableViewPager extends ViewPager {

    private OnItemClickListener mOnItemClickListener;

    public ClickableViewPager(Context context) {
        super(context);
        setup();
    }

    public ClickableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup();
    }

    private void setup() {
        final GestureDetector tapGestureDetector = new    GestureDetector(getContext(), new TapGestureListener());

        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                tapGestureDetector.onTouchEvent(event);
                return false;
            }
        });
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if(mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(getCurrentItem());
            }
            return true;
       }
    }
}

以及实现的代码onItemClickListener

ClickableViewPager viewPager = (ClickableViewPager) findViewById(R.id.viewPager);
viewPager.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                // your code
            }
        });
于 2015-10-14T10:58:29.577 回答
3

我不确定您期望通过上述听众对您做出什么回应。

您可以使用它setOnClickListener(View.OnClickListener l)来检测对 viewPager 的触摸。

您还可以使用onPageScrolled和 获取用户输入onPageSelectedonTabSelected

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}

@Override
public void onPageSelected(int position) {
    mActionBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    Object tag = tab.getTag();
    for (int i=0; i<mTabs.size(); i++) {
        if (mTabs.get(i) == tag) {
            mViewPager.setCurrentItem(i);
        }
    }
}
于 2013-05-03T03:20:50.400 回答
3

在您的活动中;你可以覆盖:

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = ev.getX();
                mDownY = ev.getY();
                break;
            case MotionEvent.ACTION_UP:
                mDownX -= ev.getX();
                mDownY -= ev.getY();
                if(mDownX==0 && mDownY==0)
                   {
                      your action if click
                   }
                break;

        }
        return super.dispatchTouchEvent(ev);
    }
于 2018-04-14T19:43:30.287 回答
2

使用事件总线。

我刚刚通过一个简单的解决方案遇到了这个问题,只需在适配器上设置一个 OnClickListener 然后发送事件。:

public Object instantiateItem(@NonNull ViewGroup container, int position) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.category_item_layout, container, false);
    ImageButton itemButton = view.findViewById(R.id.CategoryItem_ib_icon);
    itemButton.setOnClickListener(view1 -> EventBus.getDefault().postSticky(new Event(Constants.onViewPagerItem, position)));
    container.addView(view);
    return view;
}

构造函数:

    public Event(int code, int viewPagerPosition) {
    this.code = code;
    this.viewPagerPosition = viewPagerPosition;
}

注册要接收事件的活动:

EventBus.getDefault().register(this);

稍后只需通过以下方式接收事件:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(Event event) {
    if (event.getCode() == Constants.onViewPagerItem) {
        Toast.makeText(getContext(), "Item " + event.getViewPagerPosition(), Toast.LENGTH_SHORT).show();
    }
}

如果您不知道,请检查它: https ://github.com/greenrobot/EventBus

希望能帮助到你。

于 2019-06-05T14:37:21.283 回答
2
public Object instantiateItem(@NonNull final ViewGroup container, final int position)
{
    layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.slide,container,false);
    ImageView image;
    TextView title,price;
    image = view.findViewById(R.id.image_id);
    title = view.findViewById(R.id.title_id);
    price = view.findViewById(R.id.price_id);
    image.setImageResource(slidePagers.get(position).getImage());
    title.setText((CharSequence) slidePagers.get(position).getTtile());
    price.setText((CharSequence) slidePagers.get(position).getPrice());
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            if(position==0)
            {
                Intent intent = new Intent(context,getdata.class);
                context.startActivity(intent);
            }
            if(position==1)
            {
                Toast.makeText(context, "second Position", Toast.LENGTH_SHORT).show();
            }
            if(position==2)
            {
                Toast.makeText(context, "Third position ", Toast.LENGTH_SHORT).show();
            }

        }
    });
    container.addView(view,0);

    return view;
}
于 2020-04-21T17:13:14.033 回答
0

这是我的解决方案:

 @Override
public Object instantiateItem(ViewGroup container, int position) {

    MainActivity.MainImageList list = imageLists.get(position);
    String image = list.getImage();

    ImageView imageView = new ImageView(context);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

    String webImage = context.getResources().getString(R.string.websiteCapsuleImages);
    Picasso.get().load(webImage + image).into(imageView);

    View page = imageView;

    page.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            //this will log the page number that was click
            Log.i("TAG", "This page was clicked: ");
        }
    });

    container.addView(imageView, 0);
    return imageView;



}
于 2021-06-12T09:07:12.353 回答