简体   繁体   中英

Android keep selected fragment state / loaded url after orientation change,

I am new to fragments and have a lot of problems understanding and working with them. I will try to describe my problem step by step:

  • I start with a list
  • after selecting an item i start an activity with a dynamic url in a webview
  • If portrait, only the webview is showed, if landscape the list is presented next to it
  • In landscape when i select another item, it is showd in the webview (check the code)
  • Problem : When i turn back now to portrait the first selected item is showd instead of the last one.

How can i update the activity so it will keep the last opened url after orientation change?

if (fragment==null || ! fragment.isInLayout()) {

            Intent intent = new Intent(this.getActivity(), DetailViewActivity.class);
            intent.putExtra("link", urlforwebview);
            startActivity(intent);

        } else {

            DetailView detailFragment = 
                       (DetailView) 
                         getFragmentManager().findFragmentById(R.id.detailfragment);        
            detailFragment.changeWebviewURL(urlforwebview);
        } 

FIX:

Added this to my detailfragment:

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("currentUrl", url);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
            // Restore last state for checked position.
        url = savedInstanceState.getString("currentUrl", "");
        changeWebviewURL(url);
        }
    }

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