android - 在 Fragment 中更改方向时始终保留 ListView 位置

标签 android

现在,我敢肯定这对很多人来说听起来很奇怪,但我的 ListView 在旋转我的设备时始终保持其位置有一个问题。这并不是说这是一个特别糟糕的行为(这是我最终的目标,让它在用户旋转他们的设备时记住 ListView 的位置),更重要的是似乎没有理由为什么 它保留了位置。我从来没有告诉它这样做!即使当我尝试强制更改 ListView 上的自定义适配器时,它也会更新内部信息(列表项)但仍保留元素的位置。

经过进一步测试,如果我尝试制作一个延迟的 Runnable(大约延迟 300 毫秒),我可以成功更改 ArrayAdapter 并且位置重置为预期的顶部。

为什么在创建 Fragment 期间(在 onCreateView、onActivityCreated 等期间)强制 ListView 改变位置?

这是一些代码:

public class MainFragment extends Fragment {
ListView list;
ArrayList<String> skinslist;
ArrayList<File> files;
ArrayList<Integer> heights;
File directory;
String[] listitems;
LinearLayout skin_list_error;
SkinListAdapter adapter;
SwipeRefreshLayout swipeLayout;
View view;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
    listitems = getResources().getStringArray(R.array.TestStrings);
    list = (ListView) view.findViewById(R.id.skin_list);
    skin_list_error = (LinearLayout) view.findViewById(R.id.skin_list_error);

    //Initialize list items
    if (isExternalStorageWritable() && isExternalStorageReadable()) {
        directory = new File(Environment.getExternalStorageDirectory());
        //File directory = new File(getActivity().getFilesDir(), "Mine");
        directory.mkdir();
        CreateNoMediaFile.CreateNoMedia(directory);
        File[] filedirectory = directory.listFiles();

        Arrays.sort(filedirectory, new Comparator<File>(){
            public int compare(File f1, File f2)
            {
                return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
            } });

        skinslist = new ArrayList<String>();
        files = new ArrayList<File>();
        heights = new ArrayList<Integer>();
        for (File f : filedirectory) {
            String filename = f.getName();
            if (filename.endsWith(".png")) {
            skinslist.add(f.getName().substring(0, filename.length() - 4));
            files.add(f);
            }
        }
        listitems = skinslist.toArray(new String[skinslist.size()]);
            adapter = new SkinListAdapter(this.getActivity(), listitems, files, heights);
            list.setAdapter(adapter);
    } else {
        Toast.makeText(getActivity(), "Error: Couldn't access phone storage", Toast.LENGTH_LONG).show();
        list.setVisibility(ListView.GONE);
        skin_list_error.setVisibility(LinearLayout.VISIBLE);
    }
    //Finish initializing list items

    swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
    swipeLayout.setOnRefreshListener(new OnRefreshListener() {

        @Override
        public void onRefresh() {
            refreshSkins(false);
        }

    });
    swipeLayout.setColorScheme(R.color.refresh_initial_color, 
            R.color.refresh_initial_color, 
            R.color.refresh_initial_color, 
            R.color.refresh_initial_color);

}

这里是 View 膨胀的地方:

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.skinlist, container, false);
    return view;
}

最佳答案

FragmentManager 在其 moveToState() 中保存和加载 fragment 的 View 状态方法。 (搜索 saveFragmentViewState(f)f.restoreViewState())。

saveFragmentViewState() 最终为层次结构中的所有 View 调用 View.onSaveInstanceState(),因此它保存了 ListView 滚动位置, EditText 内容等等。

更新:corresponding documentation (它是关于Activity的,但是Fragment生命周期是由Activity生命周期指导的):

However, even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation calls the corresponding onSaveInstanceState() method for every View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

关于android - 在 Fragment 中更改方向时始终保留 ListView 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26289119/

相关文章:

Android 11 - 无线 ADB 配对 - Windows 机器

android - 如何从服务类调用 Activity 类

java - 使用 Robolectric,如何测试沿 POST *请求* 发送的 JSON 值

android - 在 Android 中合并音频文件的最佳方式

Android Edittext 富文本格式

Android:ADB 未加载

android - 当我添加 networkSecurityConfig 标签时,React-native android 不会构建

android - 滑动抽屉位置在调整高度时发生变化

android - Android 模拟器上的文件存储在哪里?

java - 在android中使用共享首选项存储用户名