[英]Android: how do I return to to top of RecyclerView after adding item?
我有CardViews的RecyclerView列表。 新的CardViews將插入列表的頂部。
如果“視圖”當前位於CardView列表的底部,並且我單擊“添加”按鈕以創建新的CardView,則希望RecyclerView在列表頂部顯示新的CardView。 當前,當創建新的CardView時,RecyclerView只是返回到列表底部的上一個View。
我嘗試了很多事情,沒有任何運氣,包括:
recyclerView.getLayoutManager().scrollToPosition(0);
recyclerView.scrollToPosition(0);
linearlayoutmanager.scrollToPositionWithOffset(0,0)
Adapter.java
public void add(Contact item) {
if (contactList.size()==0) {
contactList.clear();
notifyDataSetChanged();
}
contactList.add(item);
notifyItemInserted(0);
}
public void addAll(List<Contact> contactList) {
for (Contact contact : contactList) {
add(contact);
}
}
Activity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EmptyRecyclerView recyclerView = (EmptyRecyclerView)findViewById(R.id.list_recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setEmptyView(findViewById(R.id.empty_view));
contactListAdapter = new ContactListAdapter(this);
contactListAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(contactListAdapter);
@Override
protected void onStart() {
super.onStart();
loadData();
}
void loadData(){
List<Contact> contactList = new ArrayList<>();
Cursor cursor = sqLiteDB.retrieve();
Contact contact;
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
do {
contact = new Contact();
contact.setI(cursor.getInt(0));
contact.setC(cursor.getInt(1));
contact.setT(cursor.getString(2));
contact.setN1(cursor.getString(3));
contact.setN2(cursor.getString(4));
contact.setD(cursor.getString(5));
contact.setDt(cursor.getString(6));
contact.setTm(cursor.getLong(7));
// add the item to the top of the List.
contactList.add(0, contact);
} while (cursor.moveToNext());
}
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
contactListAdapter.clear();
contactListAdapter.addAll(contactList);
像這樣
recyclerview.post(new Runnable() {
@Override
public void run() {
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
layoutManager.scrollToPositionWithOffset(0, 0);
}
});
如果這不起作用,請檢查您在哪里調用此控件,然后控件執行該語句。
我將其與“滾動到頂部”按鈕一起使用,可以嘗試使用:
LinearLayoutManager mlayoutManager = (LinearLayoutManager) rv.getLayoutManager();
mlayoutManager.scrollToPositionWithOffset(0, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.