简体   繁体   English

Android:使用ViewPager时,保存每个片段中每个视图的片段状态/内容

[英]Android:Saving Fragment State/contents of each views in each Fragment when using ViewPager

I really,really need a serious help over here. 我真的非常需要这方面的认真帮助。 I am creating an android app which uses PagerAdapter to create Fragments in an activity . 我正在创建一个使用PagerAdapteractivity创建Fragments的android应用。 Different Fragment consists of different views according to need which are created during run time. 根据运行需要在运行时创建的不同片段由不同的视图组成。 In the last fragment, I have created a sort of "Submit button" , which when clicked, is supposed to get user entered values from each views(like EditText ) from all Fragments. 在上一个片段中,我创建了一种"Submit button" ,单击该"Submit button"可以从所有片段的每个视图(如EditText )中获取用户输入的值。

I am using following command to get the views(int the above mentioned button clicklistener ): 我正在使用以下命令来获取视图(上述按钮clicklistener int):

EditText e = (EditText) (getActivity().findViewById(i));

But its not geting the view with that ID except of last two fragments. 但是除了最后两个片段之外,它没有使用该ID获取视图。 So, I am assuming that, it is saving the state of only last two fragments in that activity. 因此,我假设这是在该活动中仅保存最后两个片段的状态。 So, How can I save the 'view states' of all the fragments in the activity?? 那么,如何保存活动中所有片段的'view states'

And Isn't it so that, when a view is created in a Fragment, and is added in its layout , that view is also added in the main activity layout?? 并且不是这样,当在Fragment中创建视图并添加到其布局中时,该视图也添加到了主活动布局中吗? Am I understanding it in the wrong way??Please let me know. 我以错误的方式理解它吗?请让我知道。

To simplify it, my question is: 为了简化它,我的问题是:

How can we save the contents, entered by users, in dynamically created EditText in Fragments, created using the ViewPager (So that it can be accessed later)?? 我们如何将用户输入的内容保存在使用ViewPager创建的Fragments动态创建的EditText中(以便以后可以访问)?

When you add a fragment to a FragmentPagerAdapter (assuming you haven't written a custom pager) it is added to the FragmentManager. 当您将片段添加到FragmentPagerAdapter时(假设您尚未编写自定义寻呼机),它将被添加到FragmentManager。 The Fragment manager is independent of the activity lifecycle so it retains the fragment state. 片段管理器与活动生命周期无关,因此它保留了片段状态。

If you take a look here: http://code.google.com/p/ratebeerforandroid/source/browse/trunk/JakeWharton-ActionBarSherlock/library/src/android/support/v4/app/FragmentPagerAdapter.java?spec=svn42&r=42 如果您在这里查看: http : //code.google.com/p/ratebeerforandroid/source/browse/trunk/JakeWharton-ActionBarSherlock/library/src/android/support/v4/app/FragmentPagerAdapter.java?spec=svn42&r = 42

You can get an idea of how it works. 您可以了解其工作原理。 If you want to save the fragment state for another session you'll need to pull back each fragment (getItem) and either use the onSaveInstanceState or write your own custom function 如果要为另一个会话保存片段状态,则需要拉回每个片段(getItem)并使用onSaveInstanceState或编写自己的自定义函数

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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