您好,登錄后才能下訂單哦!
要實現Spinner中選項的拖拽排序,可以通過自定義Adapter和拖拽功能來實現。以下是一個簡單的實現示例:
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);
通過以上步驟,就可以實現Spinner中選項的拖拽排序功能。需要注意的是,如果要在Spinner中使用拖拽排序,需要將Spinner替換為RecyclerView,并在RecyclerView中使用自定義Adapter和拖拽功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。