如何在我的ReccylerView适配器中将scrollToPosition(0)
添加到addItem()
方法中。要更新View,我需要参考Recyclerview?我希望将新的CardView添加到我的RecyclerView列表的顶部,并在插入新卡后让视图显示列表的顶部。请指教。
Adapter.java
...
class ListContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Context mContext;
private LayoutInflater mLayoutInflater;
private List<Contact> mContacts;
private List<ListItem> mItems;
public ListContactsAdapter(Context context, List<Contact> contacts) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContacts = contacts;
mItems = buildItemsList();
}
private List<ListItem> buildItemsList() {
List<ListItem> items = new ArrayList<>();
items.add(new ContactItem(contact));
}
public void addItem(Contact contact) {
if (mContacts.size()==0) {
mItems.clear();
notifyDataSetChanged();
}
mContacts.add(contact);
mItems.add(new ContactItem(contact));
notifyItemInserted(0);
}
以下是添加项目的活动代码:
...
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Contact contact = new Contact("", "");
mContactsAdapter.addItem(contact);
// need to figure out scrollToPosition(0) here
}
});
如果我使用recyclerView.scrollToPosition(0); Android Studio报告以下错误:&#34;变量&#39; recyclerView&#39;从内部类中访问,需要被声明为final。&#34;
答案 0 :(得分:2)
RecyclerView
有两种方法scrollToPosition
和smoothScrollToPosition
,您可以使用这些方法在notifyItemInserted()
将recyclelerview声明为Activity的成员变量,而不是方法中的局部变量,就像mContactsAdapter
一样。
示例代码:
public class XXXActivity extends Activity{
RecyclerView mRecyclerView;
// ....
public void initViews(){
mRecyclerView = (RecyclerView) findViewById(R.id.xxx);
// ....
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Contact contact = new Contact("", "");
mContactsAdapter.addItem(contact);
mRecyclerView.scrollToPosition(0);
}
});
}
// ....
}