gpt4 book ai didi

Android:如何在添加项目后返回到 RecyclerView 的顶部?

转载 作者:行者123 更新时间:2023-11-29 17:05:55 27 4
gpt4 key购买 nike

我有一个 CardView 的 RecyclerView 列表。新的 CardView 插入到列表的顶部。

如果该 View 当前位于 CardView 列表的底部,并且我单击“添加”按钮以创建新的 CardView,我希望 RecyclerView 随后在列表顶部显示新的 CardView。目前,当创建新的 CardView 时,RecyclerView 只是返回到列表底部的前一个 View 。

我已经尝试了很多东西,但没有任何运气,包括:

recyclerView.getLayoutManager().scrollToPosition(0); 
recyclerView.scrollToPosition(0);
linearlayoutmanager.scrollToPositionWithOffset(0,0)

适配器.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);
}
});

如果这不起作用,请检查您在哪里调用它,并控制是否执行该语句。

关于Android:如何在添加项目后返回到 RecyclerView 的顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com