在 Android 中,沒有名為 DataGrid 的組件
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> dataList;
public MyAdapter(List<String> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
holder.deleteButton.setOnClickListener(v -> {
// 刪除數據
dataList.remove(position);
// 通知適配器更新數據
notifyItemRemoved(position);
});
}
@Override
public int getItemCount() {
return dataList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
Button deleteButton;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
deleteButton = itemView.findViewById(R.id.deleteButton);
}
}
}
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
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> dataList = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
dataList.add("Item " + i);
}
adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
}
}
現在,當您點擊“Delete”按鈕時,應用程序將從列表中刪除相應的項目。