Ich habe eine RecyclerView-Liste von CardViews. Neue CardViews werden am Anfang der Liste eingefügt.Android: Wie kann ich nach dem Hinzufügen eines Elements zum Anfang von RecyclerView zurückkehren?
Wenn sich die Ansicht zur Zeit unten in der CardView-Liste befindet und ich auf "Hinzufügen" klicke, um ein neues CardView zu erstellen, möchte ich, dass das RecyclerView das neue CardView am Anfang der Liste anzeigt. Wenn das neue CardView erstellt wird, kehrt das RecyclerView zur letzten Ansicht am unteren Ende der Liste zurück.
ich viele Dinge ausprobiert habe, ohne Erfolg, einschließlich:
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);
Wenn Sie die Schriftrolle machen? –
Ich habe nach "layoutManager" versucht. Ich habe es auch nach "setAdapter" versucht. Ich habe auch versucht, die recyclerView nach "NotifyItemInserted (0) '" in der add() des Adapters. – AJW
Ihre 'add()' Methode ist in Recyclerview, nein? –