接收活动结果后保留片段状态

时间:2016-01-10 17:44:52

标签: android-fragments

我有一个由片段A组成的活动A.在片段A中,我用startActivityForResult()启动Activity B.当我从活动B收到结果时,片段A中的所有视图值在返回其默认值之前已经设置。如何保留Fragment A中的所有视图值?

以下是实施:

public class MainFragment extends Fragment {
public MainFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);


    listView = (ListView) getActivity().findViewById(R.id.xlistview);
    xItemArrayList = new ArrayList<XItem>();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    switch (id){
        case R.id.menu_item_add:
            initialiseList();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void initialiseList(){
    xListAdapter = new xListAdapter(getContext(), R.layout.item_list, xItemArrayList);
    xListAdapter.setxListListener(new xListListener() {
        @Override
        public void onClickStart(View view) {
            openAutocompleteActivity(Constant.VIEW_START);
        }

    });
    xListView.setAdapter(xListAdapter);
}

private void openAutocompleteActivity(int selectedView) {
    this.selectedView = selectedView;
    try {
        // The autocomplete activity requires Google Play Services to be available. The intent
        // builder checks this and throws an exception if it is not the case.
        Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(getActivity());
        startActivityForResult(intent, Constant.REQUEST_CODE_AUTOCOMPLETE);
    } catch (GooglePlayServicesRepairableException e) {
        // Indicates that Google Play Services is either not installed or not up to date. Prompt the user to correct the issue.
        GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(), 0 ).show();
    } catch (GooglePlayServicesNotAvailableException e) {
        // Indicates that Google Play Services is not available and the problem is not easily resolvable.
        String message = "Google Play Services is not available: " + GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
        Log.e(Constant.TAG_ERROR, message);
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Check that the result was from the autocomplete widget.
    if (requestCode == Constant.REQUEST_CODE_AUTOCOMPLETE) {
        if (resultCode == Constant.RESULT_OK) {
            // Get the user's selected place from the Intent.
            Place place = PlaceAutocomplete.getPlace(getActivity(), data); 
            if (selectedView == Constant.VIEW_START){
                start = place;
                ((TextView)xListView.getChildAt(0).findViewById(R.id.textview_start)).setText(start.getName());
            }else if (selectedView == Constant.VIEW_LAST){
                last = place;
                ((TextView)xListView.getChildAt(0).findViewById(R.id.textview_last)).setText(last.getName());
            }

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(getActivity(), data);
            Log.e(Constant.TAG_ERROR, "Error: Status = " + status.toString());
        } else if (resultCode == Constant.RESULT_CANCELED) {
            // Indicates that the activity closed before a selection was made. For example if
            // the user pressed the back button.
        }
    }
}

R.layout.item_list,R.id.textview_start和R.id.textview_last中有两个视图。在选择每个视图时,活动B将启动并在完成活动B后,结果将显示在视图本身上。但是,每次活动B开始和结束时,两个视图的先前值都会消失并返回默认值。我尝试过SavedInstanceState,但它不起作用。当活动B返回活动A(其中包含片段A)时,系统会转到片段A的OnResume(),而不会转到片段A的onCreatedView()。

2 个答案:

答案 0 :(得分:0)

您可以使用2种方法: 1st:使用sharedpreferences存储数据。现在,下次使用该应用程序时也可以访问此数据。因此,在显示旧数据后,只需将sharepreferences中的数据重置为空白。

第二:使用捆绑包将数据传输到活动,然后只检索相同的内容。

使用捆绑包将数据从一个活动转移到另一个活动

Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
Intent i = new Intent(this, MyActivityName.class);
i.putExtras(bundle);
startActivity(i)  <-- new activity started

然后在接收活动中:将此代码放入onCreate方法

Bundle bundle = getIntent().getExtras();
String stringdata = bundle.getString("KEY_NAME"); 

将数据从活动传递到片段:将此代码放在任何地方

Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
MyFragment myfragment = new MyFragment();
myfragment.setArguments(bundle);

然后在片段的onCreateView方法中添加此代码

Bundle args = getArguments();
String stringdata = args.getString("KEY_NAME"); 

答案 1 :(得分:0)

由于片段A正在等待活动B的结果,因此活动A(其中片段A为)将进入暂停状态。当活动B返回结果时,片段A将在不经过onActivityCreated()的情况下恢复。因此,保存实例状态将不起作用。目前,我能想到的唯一解决方案如下。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// Check that the result was from the autocomplete widget.
if (requestCode == Constant.REQUEST_CODE_AUTOCOMPLETE) {
    if (resultCode == Constant.RESULT_OK) {
        // Get the user's selected place from the Intent.
        Place place = PlaceAutocomplete.getPlace(getActivity(), data); 
        if (selectedView == Constant.VIEW_START){
            start = place;
        }else if (selectedView == Constant.VIEW_LAST){
            last = place;
        }

    } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
        Status status = PlaceAutocomplete.getStatus(getActivity(), data);
        Log.e(Constant.TAG_ERROR, "Error: Status = " + status.toString());
    } else if (resultCode == Constant.RESULT_CANCELED) {
        // Indicates that the activity closed before a selection was made. For example if
        // the user pressed the back button.
    }
}

if(start!=null)((TextView)xListView.getChildAt(0).findViewById(R.id.textview_start)).setText(start.getName());    
if(last!=null)((TextView)xListView.getChildAt(0).findViewById(R.id.textview_last)).setText(last.getName());

}

所有视图值都在onActivityResult()中重新设置。当活动A /片段A进入​​暂停状态时,它会保留全局变量值。因此,要使此实现起作用,必须在片段A中将start和last声明为全局变量。如果有的话,请提出更好的解决方案。