溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spinner實(shí)現(xiàn)選項的拖拽排序與位置記憶

發(fā)布時間:2024-08-16 17:29:29 來源:億速云 閱讀:79 作者:小樊 欄目:移動開發(fā)

要實(shí)現(xiàn)Spinner選項的拖拽排序與位置記憶,可以通過自定義Adapter來實(shí)現(xiàn)。下面是一個簡單的示例代碼:

public class DragSortSpinnerAdapter extends ArrayAdapter<String> implements View.OnTouchListener {

    private SparseBooleanArray selectedItems;
    private int lastPosition = -1;

    public DragSortSpinnerAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
        selectedItems = new SparseBooleanArray();
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        View view = super.getDropDownView(position, convertView, parent);
        view.setTag(position);
        view.setOnTouchListener(this);
        return view;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        View view = (View) v.getParent();
        int position = (int) view.getTag();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastPosition = position;
                break;

            case MotionEvent.ACTION_MOVE:
                if(lastPosition != -1 && lastPosition != position) {
                    String item = getItem(lastPosition);
                    remove(item);
                    insert(item, position);
                    selectedItems.clear();
                    selectedItems.put(position, true);
                    notifyDataSetChanged();
                    lastPosition = position;
                }
                break;

            default:
                lastPosition = -1;
                break;
        }

        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if(selectedItems.get(position)) {
            view.setBackgroundColor(Color.LTGRAY);
        } else {
            view.setBackgroundColor(Color.TRANSPARENT);
        }
        return view;
    }
}

在使用Spinner時,可以使用這個自定義Adapter來實(shí)現(xiàn)拖拽排序和位置記憶的功能。當(dāng)用戶在Spinner選項上按下并移動時,會觸發(fā)onTouch方法,Adapter會根據(jù)移動的位置重新排序選項,并在getView方法中根據(jù)selectedItems來設(shè)置選中項的背景色。這樣就可以實(shí)現(xiàn)Spinner選項的拖拽排序與位置記憶功能了。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI