我想在我的应用中实现“新”数据绑定,但我被卡住了。我有一个数据库,我保存了联系人,所以我需要从另一个片段中获取数据并在recycleler视图中显示它们。 SO:片段与回收者视图 - >点击AddButton - >用editTexts打开新片段 - >填写editTexts - >保存到数据库 - >显示在上一个片段中(使用该回收站视图) 我已经完成了适配器,但我不知道如何在我的片段中设置它。请问你能帮帮我吗?
模型
public class Contact extends SugarRecord {
public String name;
private String number;
private String email;
private boolean isFavourite;
public Contact() {
}
public Contact(String name, String email, String number, Boolean isFavourite) {
this.name = name;
this.email = email;
this.number = number;
this.isFavourite = isFavourite;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setNumber(String number) {
this.number = number;
}
public void setFavourite(Boolean isFavourite) {
this.isFavourite = isFavourite;
}
@Bindable
public String getName() {
return name;
}
@Bindable
public String getEmail() {
return email;
}
@Bindable
public String getNumber() {
return number;
}
@Bindable
public boolean getFavourite() {
return isFavourite;
}
}
适配器
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private List<Contact> mContacts;
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
}
public ViewDataBinding getBinding() {
return binding;
}
}
public ContactsRecyclerAdapter(List<Contact> recyclerUsers) {
this.mContacts = recyclerUsers;
}
@Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
@Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContacts.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
@Override
public int getItemCount() {
return mContacts.size();
}
}
我想要回收者视图的片段
public class ContactListFragment extends Fragment implements View.OnClickListener {
private static final String NEWCONTACT = "newcontact";
FloatingActionButton fabButton;
SearchView searchView;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
return view;
}
----- other stuff in the fragment ------
答案 0 :(得分:0)
尝试在RecyclerView
的{{1}}方法中初始化onCreateView
,如下所示
ContactListFragment
这样您可以将适配器设置为片段中的Recycler视图。