以下是一个示例代码,演示如何在Android中获取用户输入并在RecyclerView中显示:
首先,在布局文件中定义一个EditText和一个Button,用于用户输入和提交操作:
然后,在Java代码中实现RecyclerView的适配器和数据模型类。假设数据模型类为Item
,包含一个字符串属性text
:
public class Item {
private String text;
public Item(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
RecyclerView的适配器ItemAdapter
继承自RecyclerView.Adapter
,负责管理数据集合和视图的创建和绑定:
public class ItemAdapter extends RecyclerView.Adapter {
private List- itemList;
public ItemAdapter(List
- itemList) {
this.itemList = itemList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Item item = itemList.get(position);
holder.textView.setText(item.getText());
}
@Override
public int getItemCount() {
return itemList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
接下来,在Activity或Fragment中获取用户输入,创建RecyclerView和适配器,并将适配器设置给RecyclerView:
public class MainActivity extends AppCompatActivity {
private List- itemList;
private ItemAdapter itemAdapter;
private EditText editTextInput;
private Button buttonSubmit;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化数据集合和适配器
itemList = new ArrayList<>();
itemAdapter = new ItemAdapter(itemList);
// 获取布局中的视图
editTextInput = findViewById(R.id.edit_text_input);
buttonSubmit = findViewById(R.id.button_submit);
recyclerView = findViewById(R.id.recycler_view);
// 设置RecyclerView的布局管理器和适配器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(itemAdapter);
// 设置按钮点击事件,获取用户输入并更新RecyclerView
buttonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputText = editTextInput.getText().toString();
Item item = new Item(inputText);
itemList.add(item);
itemAdapter.notifyDataSetChanged();
editTextInput.setText(""); // 清空输入框
}
});
}
}
以上代码示例演示了如何获取用户输入并将其显示在RecyclerView中。用户在EditText中输入内容后,点击按钮,程序会将输入内容添加到数据集合中,并通知适配器更新RecyclerView的显示。