如何实现Android GridView多选择?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (159)

我想用GridView布局做一个活动,将能够在Gridview元素上拖动手指的多项选择,要怎样才能实现呢?

提问于
用户回答回答于

可以这样试试:

...
private final int SELECTED_CELL_COLOR = Color.GREEN;
private int mPosition = GridView.INVALID_POSITION;
private boolean mSelecting = false;
...
@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getActionMasked();
    switch (action){
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_UP:
        int x = (int)event.getX();
        int y = (int)event.getY();
        GridView grid = (GridView)v;
        int position = grid.pointToPosition(x, y);
        if(position != GridView.INVALID_POSITION) {
            v.getParent().requestDisallowInterceptTouchEvent(true); //Prevent parent from stealing the event
            View cellView = (View)grid.getItemAtPosition(position);
            switch (action){
            case MotionEvent.ACTION_DOWN:
                mSelecting = true;
                mPosition = position;
                cellView.setBackgroundColor(SELECTED_CELL_COLOR);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mPosition != position) {
                    mPosition = position;
                    cellView.setBackgroundColor(SELECTED_CELL_COLOR);
                } else {
                    //Repeated cell, noop
                }
                break;
            case MotionEvent.ACTION_UP:
                mSelecting = false;
                mPosition = GridView.INVALID_POSITION;
                //Here you could call a listener, show a dialog or similar
                break;
            }
        }else{
            if(mSelecting){
                mSelecting = false;
            }
        }
    break;
    case MotionEvent.ACTION_CANCEL:
        mSelecting = false;
        break;
    }
    return true;
}

扫码关注云+社区

领取腾讯云代金券