ListView行中的ViewPager可防止触发onItemClick

时间:2015-04-14 08:02:22

标签: android android-viewpager

我在ListView的每一行中都有一个ViewPager。它工作正常,当用户使用滑动手势时,它会更改其中的视图,但它会阻止调用ListView的onItemClick方法。我知道ViewPager是罪魁祸首,因为当我隐藏它时,会调用onItemClick,所以这就是我想要的:

我创建了一个ViewGroup作为行(RowView)。此ViewGroup具有onInterceptTouchEvent覆盖,以避免ViewPager在检测到点击时处理更多触摸事件。但仍未调用onItemClick回调。并且列表选择器不会在点击时显示。我想要这两个功能。

这是RowView的onInterceptTouchEvent的样子:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    int actionMasked = ev.getActionMasked();
    switch(actionMasked) {
        case MotionEvent.ACTION_DOWN:
            Log.d("RowView", "OnInterceptTouchEvent - Down");
            tapDetector.onTouchEvent(ev);
            return false;
        case MotionEvent.ACTION_CANCEL:
            Log.d("RowView", "OnInterceptTouchEvent - Cancel");
            tapDetector.onTouchEvent(ev);
            break;
        case MotionEvent.ACTION_UP:
            if(tapDetector.onTouchEvent(ev)) {
                Log.d("RowView", "OnInterceptTouchEvent - UP!");
                return true;
            }
            break;
    }

    return super.onInterceptTouchEvent(ev);
}

有任何解决此问题的建议吗?

编辑:关于如何在ViewPager处于活动状态时未调用MainActivity中的onItemClick的示例(Lollipop列表选择器也不会出现)

  

MainActivity

ListView listView = (ListView) findViewById(R.id.main_list);
listView.setAdapter(new MainListAdapter(this, 30));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "onItemClick: " + position);
    }
});
  

列出项目XML:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:descendantFocusability="blocksDescendants"
    >

    <TextView
        android:id="@+id/row_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />

    <android.support.v4.view.ViewPager
        android:id="@+id/row_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        />
</RelativeLayout>
  

列表适配器:

public class MainListAdapter extends BaseAdapter {
    private Context context;
    private LayoutInflater inflater;
    private int count;

    public MainListAdapter(Context context, int count) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.count = count;
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if(convertView == null) {
            holder = new ViewHolder();
            convertView = createRow(parent, holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.textView.setText(Integer.toString(position));
        int randomPages = (int) (new Random().nextDouble()*5+2);
        holder.viewPager.setAdapter(new NumAdapter(context, randomPages));

        return convertView;
    }

    private View createRow(ViewGroup parent, ViewHolder holder) {
        View view = inflater.inflate(R.layout.row_main_listview, parent, false);
        holder.textView = (TextView) view.findViewById(R.id.row_num);
        holder.viewPager = (ViewPager) view.findViewById(R.id.row_viewpager);
        view.setTag(holder);

        return view;
    }

    private static class ViewHolder {
        public TextView textView;
        public ViewPager viewPager;
    }
}
  

ViewPager的适配器:

public class NumAdapter extends PagerAdapter {
    private LayoutInflater inflater;
    private int count;

    public NumAdapter(Context context, int count) {
        this.inflater = LayoutInflater.from(context);
        this.count = count;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        TextView textView = (TextView) inflater.inflate(R.layout.page_viewpager, container, false);
        textView.setText("Page " + position);
        container.addView(textView);
        return textView;
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }
}

9 个答案:

答案 0 :(得分:5)

我认为更好的覆盖列表视图onintercepter而不是viewgroup。

TouchEvent Flow简单:

活动触摸事件 - &gt; viewgroup.dispatchtouchevent - &gt; viewgroup.intercepter ..-&GT; view.dispatchtouch ... - &gt; .....

在这种情况下list.dispatch调用。将事件投掷到ViewPager.dispatch。但在ViewPager.dispatchtouchevent之前,请致电ListView.intercepterTouchEvent

如果dispatchTouchEvent返回false致电父View&#39; TouchEvent但返回true来电流量下降。

如果intercepterTouchEvent返回true,则不要给孩子dispatchTouchEvent打电话,但要回复false来电儿童dispatchTouchEvent。 所以listview.intercepterTouchEvent返回true,调用o nItemClick

所以如果listView.intercepterTouchEvent返回true,则不会刷viewPager项。

您可以了解用户的动作滑动或点击2方式。 TouchEventguesturedetector ..

列表视图中的

IntercepterTouchEvent(Event ev);

VelocityTracker mVelocityTracker;
PointF mLastPoint;
public mListView(Context context) {
    super(context);
    init();
}

public mListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public mListView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init(){
    mLastPoint = new PointF();
}


@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {

    if(mVelocityTracker == null)
        mVelocityTracker = VelocityTracker.obtain();
    mVelocityTracker.addMovement(ev);

    switch (ev.getAction()){
        case MotionEvent.ACTION_MOVE:
            mVelocityTracker.computeCurrentVelocity(100);
            int x = (int)Math.abs(mVelocityTracker.getXVelocity());
            int move_x = (int)Math.abs(ev.getX() - mLastPoint.x);
            Log.d("ListView","speed : " + x +" move_x : " + move_x);
            //here x is drag speed. (pixel/s)
            // change value left right both value you want speed and move amount
            if(move_x < 100 || x <100) {
                mLastPoint.set(ev.getX(), ev.getY());
                return true;
            }
            break;
        case MotionEvent.ACTION_DOWN:
            mLastPoint.set(ev.getX(), ev.getY());
            break;
        case MotionEvent.ACTION_UP:

            mVelocityTracker.recycle();mVelocityTracker = null;

            break;
    }
    return super.onInterceptTouchEvent(ev);
}

你可以快速扫描100或移动量100像素。如果没有执行点击事件。

我希望这篇文章可以帮助你......

并添加编辑一些代码。

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {

    if(mVelocityTracker == null)
        mVelocityTracker = VelocityTracker.obtain();
    mVelocityTracker.addMovement(ev);

    switch (ev.getAction()){
        case MotionEvent.ACTION_MOVE:
            mVelocityTracker.computeCurrentVelocity(10);
            int x = (int)Math.abs(mVelocityTracker.getXVelocity());
            int move_x = (int)Math.abs(ev.getX() - mLastPoint.x);
            int move_y = (int)Math.abs(ev.getY() - mLastPoint.y);
            Log.d("ListView","speed : " + x +" move_x : " + move_x + " move_y : "+ move_y);
            if(move_x < move_y || x < 10) {
                mLastPoint.set(ev.getX(), ev.getY());
                return true;
            }else if(move_x > move_y){
                return false;
            }
            break;
        case MotionEvent.ACTION_DOWN:
            mLastPoint.set(ev.getX(), ev.getY());
            break;
        case MotionEvent.ACTION_UP:
            break;
    }
    return super.onInterceptTouchEvent(ev);
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.d("ListView", "dispatch");
    switch (ev.getAction()){
        case MotionEvent.ACTION_MOVE:
            break;
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_UP:
            if(mVelocityTracker != null){mVelocityTracker.recycle();mVelocityTracker = null;}
            break;
    }
    return super.dispatchTouchEvent(ev);;
}

答案 1 :(得分:3)

由于您的视图是listview的孩子,因此会消耗触摸事件。你可以通过使你的观看者孩子不可点击来防止这种情况,即

    TextView textView =(TextView)inflater.inflate(R.layout.page_viewpager,container, false);

    textView.setText("Page " + position); 

    textView.setClickable(false);

答案 2 :(得分:3)

我建议在每个Link Binary with Libraries实例上设置OnClickListener,并避免使用ListView的ViewPager。然后,您也可以完全删除onItemClickListener。那将是最简单和稳定的解决方案。更少的代码 - 更少的错误;)

答案 3 :(得分:2)

您需要执行以下操作之一:

setOnClickListener的孩子上设置Viewpager或找到

android:descendantFocusability="beforeDescendants"

我希望这对你有所帮助。

答案 4 :(得分:2)

我认为这应该可以解决问题。

viewPager.getParent().requestDisallowInterceptTouchEvent(false);

我希望这会对你有所帮助。

答案 5 :(得分:2)

我们的想法是在视图寻呼机而不是listView

上进行点击监听

在getView方法中添加viewPager时,将其标记设置为行的位置

holder.viewPager.setTag(position);

然后将click监听器添加到viewPager(也在getView中)

viewPager.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        int position = v.getTag();
        Log.d(TAG, "onItemClick: " + position);

        //Fire a delegate or notification of whatever you want to do on the item click. You now have the position
        myClickListener.onItemClicked(position);

    }
});

答案 6 :(得分:2)

问题在于列表适配器视图。当我尝试实现相同的功能(listview在listview行中)时,我遇到了类似的问题。我这样解决了---- 在viewholder对象上设置onclicklistener,而不是直接在listview上设置。为此,您必须在适配器类上实现onitemclicklistener。

答案 7 :(得分:1)

对阿德里安答案的改进:

a = [[1,2], [3,4], [4,2], [2,1]]

count = Hash.new(0)

a.map do |r|
  # Expand each entry of the form [1,2]
  # to [ [1,2], [[1,0],[2,1]]
  [ r, r.each_with_index.to_a ]
end.each do |r, p|
  # Tabulate how many of the number+position values occur
  p.each do |x|
    count[x] += 1
  end
end.select do |r, p|
  # Only select entries where all number+position values are unique.
  p.all? do |x|
    count[x] == 1
  end
end.map do |r, p|
  # Extract the original data
  r
end

# => [[3, 4], [2, 1]]

答案 8 :(得分:0)

虽然列表选择器不起作用,但这是我最终要做的事情。这可以改进,但是,目前,它是我唯一喜欢的工作方式。

public class CustomListView extends ListView implements AbsListView.OnScrollListener {
    /*
     *  Used for detect taps
     */
    private GestureDetector tapDetector;
    /*
     *  As we need to set our own OnScrollListener, this stores the one 
     *  used outside, if any
     */
    private OnScrollListener onScrollListener;

    private boolean isScrolling = false;

    public CustomListView(Context context) {
        super(context);
        initView(context);
    }

    public CustomListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CustomListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CustomListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
    }

    private void initView(Context context) {
        tapDetector = new GestureDetector(context, new TapListener());
        super.setOnScrollListener(this);
    }

    @Override
    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.onScrollListener = onScrollListener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean isTap = tapDetector.onTouchEvent(ev);

        if(ev.getActionMasked() == MotionEvent.ACTION_UP) {
            // Don't perform the click if the ListView is scrolling
            // so it is able to stop the scroll
            if(isTap && !isScrolling && hasOnItemClickListener()) {
                int itemPosition = pointToPosition((int)ev.getX(), (int)ev.getY());
                performItemClick(this, itemPosition, getItemIdAtPosition(itemPosition));
            }
        }

        return super.dispatchTouchEvent(ev);
    }

    public boolean hasOnItemClickListener() {
        return getOnItemClickListener() != null;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        isScrolling = scrollState != OnScrollListener.SCROLL_STATE_IDLE;

        if(this.onScrollListener != null) {
            onScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if(this.onScrollListener != null) {
            onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
        }
    }