2015-05-14 18 views
7

Làm cách nào để lưu vị trí cuộn của ListView khi tôi chọn một mục trong ListView và tôi muốn quay trở lại trong cùng một ListView.Làm cách nào để lưu vị trí cuộn của ListView

Giả sử chúng tôi có hai đoạn - ListFragment và SomeOtherFragment. Chúng tôi thay thế ListFragment bằng SomeOtherFragment.

FragmentManager manager = getFragmentManager(); 
    FragmentTransaction transaction = manager.beginTransaction(); 

    transaction.replace(R.id.content_frame, fragment); 
    transaction.addToBackStack(null); 
    transaction.commit(); 

Trả lời

9

Giải pháp tốt nhất mà tôi biết

// Save the bang ListView (= bao gồm vị trí cuộn) như là một Parcelable

Parcelable state = listView.onSaveInstanceState(); 

// Khôi phục trạng thái trước đó (bao gồm cả chỉ số mục được chọn và cuộn vị trí)

listView.onRestoreInstanceState(state); 

Bạn cũng có thể khôi phục vị trí đã lưu cuối cùng ngay cả sau khi thanh toán ing adapter as -

// Save the ListView state (= includes scroll position) as a Parceble 
Parcelable state = listView.onSaveInstanceState(); 

// e.g. set new items 
listView.setAdapter(adapter); 

// Restore previous state (including selected item index and scroll position) 
listView.onRestoreInstanceState(state); 

Bạn cũng có thể tham khảo here để biết thêm chi tiết.

2

Khi bạn bấm vào hàng ListFragment, lưu vị trí trong SharedPreference

<shared_pref_object>.putInt("scroll_position",position); 

Sử dụng này khi bạn trở về từ OtherFragment ->ListFragment

<editor_obj>.getInt("scroll_position",0); 

bộ này như vị trí cuộn:

listview.setSelection(<editor_obj>.getInt("scroll_position",0)); 
1

Tôi thực sự thắc mắc r lý do tại sao cho vấn đề phổ biến này không có giải pháp tốt và tối ưu. Như tôi đã thấy, mọi người đã giải quyết nó theo cách riêng của mình. nhưng tôi muốn trình bày theo cách riêng của tôi sau khi thử tất cả trong số họ:

Trong ListFragment tuyên bố hai biến int để giữ vị trí cuộn:

public static class MyListFragment extends ListFragment { 

     private int listIndex = -1; 
     private int listTop = 0; 

Sau đó ghi đè lên onPause() và onResume() để lưu và khôi phục các vị trí cuộn của ListView như sau:

@Override 
public void onResume() { 
     super.onResume(); 

    //after setting adapter and your arbitrary codes 
     if(listIndex!=-1){ 
     this.getListView().setSelectionFromTop(index, top); 
     } 

} 

@Override 
public void onPause() { 
     super.onPause(); 
     try { 
     listIndex = getListView().getFirstVisiblePosition(); 
     View v = getListView().getChildAt(0); 
     listTop = (v != null) ? v.getTop() : 0; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

Muốn giảm thiểu các cơn đau !! : đỏ mặt:

Các vấn đề liên quan