在使用活动中嵌入的碎片时,我发现了大量有关恢复应用程序状态的正确方法的相互矛盾的信息。如果我的架构是问题,请告诉我,因为这是完全可能的。我的测试天气应用程序的架构如下。
主要活动“ReportsActivity”包含片段“ReportsFragment”(这是接下来10天的天气报告列表) ReportsFragment有一个onItemClickListener,它启动一个新的Activity“WeatherDetailActivity”并传递一个intent,其中包含一些我用来填充Weather Detail UI的JSON数据。然后,此数据将显示在WeatherDetailActivity管理的片段上。
我的问题是,当用户按下后退按钮时,ReportsFragment已被销毁,因此它会在整个生命周期内运行。我已经尝试了一些我在网上发现的从捆绑中加载活动数据的技术,但无论我到目前为止尝试过什么,在ReportsActivity的onCreate方法中,Intents的Extras都是null。 (注意:我需要这样做的原因是为了避免每次打开我的主要活动时触发API调用,该活动从Weather Underground获取天气数据)。
我正在努力确定构建此应用程序的最佳方法:我是否应该推送一个活动来推送和弹出它管理的碎片?或者是多个活动,每个活动都管理自己的片段标准做法?
目前,我正在尝试将我的应用程序状态保存到intent上。我正在尝试从我的AsyncTask中保存onPostExecute中的状态,所以在我从API调用中获取结果后,我在主线程上:
@Override
protected void onPostExecute(Report[] result){
if (result != null){
ArrayList<String>reportsArrayList = new ArrayList<String>();
Gson jsonArray = new GsonBuilder().setPrettyPrinting().create();
for (int x = 0; x < result.length; x++){
reportsArrayList.add(jsonArray.toJson(result[x], Report.class));
}
mExtras.putStringArrayList(ReportsActivity.ReportsActivityState.KEY_ACTIVITY_REPORTS,reportsArrayList);
}
}
然后我尝试从ReportsActivity的onCreate方法恢复状态:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reports);
if (savedInstanceState == null) {
Intent intent = getIntent();
mFragment = ReportsFragment.newInstance(intent
.getStringArrayListExtra(ReportsActivityState.KEY_ACTIVITY_REPORTS));
getFragmentManager().beginTransaction()
.add(R.id.container, mFragment).commit();
}
}
在所有情况下,StringArrayListExtra我试图从intent返回null。
这很可能是我尝试用iOS思维解决Android问题,但是在推送详细视图之前,还没有一种简单的方法可以将主要活动恢复到原来的状态吗?
答案 0 :(得分:1)
我认为看看EventBus是值得的。
基本上,您可以定义任何类型的对象持有者,例如:
class WeatherData {
List<String> reports;
public WeatherData(List<String> reports) {
this.reports = reports;
}
}
现在,在您希望记住状态的活动或片段中,或将某个状态传递给另一个活动或片段:
// this removes all the hazzle of creating bundles etc
EventBus.getDefault().postSticky(new WeatherData(reports));
您希望了解最新WeatherData的代码中的任何位置:
WeatherData weatherData = EventBus.getDefault().getSticky(WeatherData.class);
EventBus还有很好的事件处理方法(按钮点击,完成长时间运行的流程等)。
可在此处找到该库:https://github.com/greenrobot/EventBus
此处还有一些示例:http://awalkingcity.com/blog/2013/02/26/productive-android-eventbus/
不使用3.零件库的一些建议:
1)在片段onCreate方法中调用setRetainInstance(true),这应该做的是在实例之间保持公共变量。
虽然它似乎不适用于后台堆栈上的片段:Understanding Fragment's setRetainInstance(boolean)
2)将片段数据传递给您的Activity,例如读取/更新((YourActivity)getActivity())。someFragmentBundle,可能将其保存在Activity的onSaveInstanceState中并在onCreate中检索它。也就是说,让您的Activity保存实例之间的数据。
3)您还可以保留数据,将其保存到文件或使用SharedPreferences http://developer.android.com/training/basics/data-storage/index.html
此方法的优势在于即使在完全终止您的应用后也可以恢复数据。
建筑问题
免责声明:主观意见
我通常会说将“活动”保持为“苗条”状态。尽可能地保留一系列相关的碎片。
因此,拥有多个活动是合适的,但他们应该管理一组(或单个)与当前活动相关的相关片段。
答案 1 :(得分:0)
我刚刚看到了Google提供的一个我经常忽略的Android Studio模板。从谷歌自己的模板中可以清楚地看出,主细节活动/碎片的首选方法是让每个碎片由他们自己的活动管理(正如我上面试图实现的那样)。
(我应该注意到,我能够成功地实现流程,我希望使用一个包含多个片段的Activitiy并自定义动画并强制显示和隐藏向上按钮。)
<强> PersonListActivity.java 强>
public class PersonListActivity extends Activity
implements PersonListFragment.Callbacks {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person_list);
if (findViewById(R.id.person_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((PersonListFragment) getFragmentManager()
.findFragmentById(R.id.person_list))
.setActivateOnItemClick(true);
}
// TODO: If exposing deep links into your app, handle intents here.
}
/**
* Callback method from {@link PersonListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
@Override
public void onItemSelected(String id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PersonDetailFragment.ARG_ITEM_ID, id);
PersonDetailFragment fragment = new PersonDetailFragment();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.replace(R.id.person_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, PersonDetailActivity.class);
detailIntent.putExtra(PersonDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
}
PersonListFragment.java
public class PersonListFragment extends ListFragment {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PersonListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: replace with a real list adapter.
setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(
getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
DummyContent.ITEMS));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
<强> PersonDetailActivity.java 强>
public class PersonDetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person_detail);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(PersonDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(PersonDetailFragment.ARG_ITEM_ID));
PersonDetailFragment fragment = new PersonDetailFragment();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.add(R.id.person_detail_container, fragment)
.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, PersonListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
<强> PersonDetailFragment.java 强>
public class PersonDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private DummyContent.DummyItem mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PersonDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_person_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.person_detail)).setText(mItem.content);
}
return rootView;
}
}