Maintain/Save/Restore scroll position when returning to a ListView

后端 未结 20 1654
無奈伤痛
無奈伤痛 2020-11-21 21:30

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the

20条回答
  •  灰色年华
    2020-11-21 22:20

    My answer is for Firebase and position 0 is a workaround

    Parcelable state;
    
    DatabaseReference everybody = db.getReference("Everybody Room List");
        everybody.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                state = listView.onSaveInstanceState(); // Save
                progressBar.setVisibility(View.GONE);
                arrayList.clear();
                for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                    Messages messagesSpacecraft = messageSnapshot.getValue(Messages.class);
                    arrayList.add(messagesSpacecraft);
                }
                listView.setAdapter(convertView);
                listView.onRestoreInstanceState(state); // Restore
            }
    
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    

    and convertView

    position 0 a add a blank item that you are not using

    public class Chat_ConvertView_List_Room extends BaseAdapter {
    
    private ArrayList spacecrafts;
    private Context context;
    
    @SuppressLint("CommitPrefEdits")
    Chat_ConvertView_List_Room(Context context, ArrayList spacecrafts) {
        this.context = context;
        this.spacecrafts = spacecrafts;
    }
    
    @Override
    public int getCount() {
        return spacecrafts.size();
    }
    
    @Override
    public Object getItem(int position) {
        return spacecrafts.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    @SuppressLint({"SetTextI18n", "SimpleDateFormat"})
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.message_model_list_room, parent, false);
        }
    
        final Messages s = (Messages) this.getItem(position);
    
        if (position == 0) {
            convertView.getLayoutParams().height = 1; // 0 does not work
        } else {
            convertView.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
        }
    
        return convertView;
    }
    }
    

    I have seen this work temporarily without disturbing the user, I hope it works for you

提交回复
热议问题