在 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”按钮时,应用程序将从列表中删除相应的项目。