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

后端 未结 20 1634
無奈伤痛
無奈伤痛 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:05

    To clarify the excellent answer of Ryan Newsom and to adjust it for fragments and for the usual case that we want to navigate from a "master" ListView fragment to a "details" fragment and then back to the "master"

        private View root;
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
               if(root == null){
                 root = inflater.inflate(R.layout.myfragmentid,container,false);
                 InitializeView(); 
               } 
               return root; 
            }
    
        public void InitializeView()
        {
            ListView listView = (ListView)root.findViewById(R.id.listviewid);
            BaseAdapter adapter = CreateAdapter();//Create your adapter here
            listView.setAdpater(adapter);
            //other initialization code
        }
    

    The "magic" here is that when we navigate back from the details fragment to the ListView fragment, the view is not recreated, we don't set the ListView's adapter, so everything stays as we left it!

提交回复
热议问题