简体   繁体   中英

Using FragmentStatePagerAdapter

I have some confusion when learning swipe views. I don't understand what does the position in getItem(int position) do, what does it refer to? The position in the adapter? The document says getItem(int position) only gets called when the fragment doesn't exist and what does this mean?

I learned how to use ArrayAdapter and we have to pass an array into an ArrayAdapter but why don't we need to pass an array of fragment into FragmentStatePagerAdapter?

And lastly, what I want to do is: I have a ListView containing several items and if I click into it, it would simply show the item name in another activities(which is already done),then I could swipe left and right to view the other items in the list. How could I do that? Do I also need to get the item position in the ListView?

Well, from my experience the getItem(int position) returns what you want it to return. You can see that the return type of the method is Object so you can send anything from that method. Now if I am not wrong, what your need is on the click of each ListView item, you want to get the text of the the item and getItem(int position) is exactly what you need.

Suppose you have an arraylist called listViewText . Then you can define the above method as

@Override
public Object getItem(int position){
    return listViewText.get(position);
}

and from the calling activity you can invoke it when the item is clicked

String listItemText;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             listItemText=adapter.getItem(position);
        }
    });

where adapter is your ListView adapter

Update

That was for the ListView adapters. Now regarding your confusion about FragmentStatePagerAdapter , I think what the documentation trying to say is that, in order to reduce the memory consumption as in the FragmentPagerAdapter , the adapter uses the getItem(int position) method only at the start when there is no state of the fragment is available. It means for the first time the fragment is loaded. Now when the particular fragment is swiped away, the adapter saves the current states of the fragment (contents ,etc) and when later the fragment is swiped in, the adapter will restore the saved states rather than creating new fragment and hence calls the method only one time.

Note that, the adapter may also call the getItem(int position) if somehow the states of the particular fragment is lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM