您好,登錄后才能下訂單哦!
要實(shí)現(xiàn)Spinner中選項(xiàng)的拖拽排序,可以通過自定義Adapter和拖拽功能來實(shí)現(xiàn)。以下是一個簡單的實(shí)現(xiàn)示例:
public class CustomSpinnerAdapter extends BaseAdapter {
private Context mContext;
private List<String> mItems;
public CustomSpinnerAdapter(Context context, List<String> items) {
mContext = context;
mItems = items;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(android.R.layout.simple_spinner_item, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(mItems.get(position));
return convertView;
}
}
List<String> items = new ArrayList<>();
items.add("Option 1");
items.add("Option 2");
items.add("Option 3");
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, items);
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(adapter);
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
// Swap the items in the list
Collections.swap(items, fromPosition, toPosition);
adapter.notifyDataSetChanged();
return true;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
// Not needed for drag and drop sorting
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
通過以上步驟,就可以實(shí)現(xiàn)Spinner中選項(xiàng)的拖拽排序功能。需要注意的是,如果要在Spinner中使用拖拽排序,需要將Spinner替換為RecyclerView,并在RecyclerView中使用自定義Adapter和拖拽功能。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。