我的活动中有一个RecyclerView,我想向其中添加EditText条目(来自Custom AlertDialog)。 Custom AlertDialog具有一个EditText和一个用于保存名称的按钮。
执行此操作的最佳方法是什么?我应该为AlertDialog创建一个适配器类还是可以在MainActivity类中进行设置?
以下是代码:
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
}
private void setupViews() {
RecyclerView recyclerView = findViewById(R.id.rv_main);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
ContactAdapter contactAdapter = new ContactAdapter();
recyclerView.setAdapter(contactAdapter);
Button addNewContactButton = findViewById(R.id.btn_main_newContact);
}
联系方式:
public class Contact {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ContactAdapter:
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<Contact> contacts = new ArrayList<>();
public ContactAdapter() {
}
@NonNull
@Override
public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_contact,parent,false);
return new ContactViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
holder.bindContact(contacts.get(position));
}
@Override
public int getItemCount() {
return contacts.size();
}
public void addContact(Contact contact){
this.contacts.add(contact);
notifyItemInserted(this.contacts.size()-1);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public ContactViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.tv_itemContact);
}
public void bindContact(Contact contact){
nameTextView.setText(contact.getName());
}
}
}