在 Android 中,要實現一個多選項視圖并進行快捷操作,可以使用 RecyclerView 和 CheckBox
build.gradle
文件中添加 RecyclerView 依賴項:dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
activity_main.xml
)中添加 RecyclerView: android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
list_item.xml
),并添加一個 CheckBox: android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Option"/>
MyAdapter.java
),繼承自 RecyclerView.Adapter
:public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> options;
public MyAdapter(List<String> options) {
this.options = options;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.checkBox.setText(options.get(position));
}
@Override
public int getItemCount() {
return options.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
public ViewHolder(View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkBox);
}
}
}
MainActivity.java
)中設置 RecyclerView 和適配器:public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> options = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
options.add("Option " + i);
}
adapter = new MyAdapter(options);
recyclerView.setAdapter(adapter);
}
}
現在,你應該有一個帶有多個選項的 RecyclerView,每個選項都有一個 CheckBox。用戶可以通過點擊 CheckBox 來選擇或取消選擇選項。如果需要獲取所有選定的選項,可以在適配器中添加一個方法來遍歷所有選項并返回選定的選項。