获取当前片段并保存在onSaveInstanceState()方法上以进行屏幕定向 [英] Get Current Fragment and Save on onSaveInstanceState() Method For Screen Orientation

本文介绍了获取当前片段并保存在onSaveInstanceState()方法上以进行屏幕定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个片段的活动。我还在我的选项卡上使用actionbarSherlock,这些选项卡也连接到片段。

I have one Activity with multiple Fragments. I am also using actionbarSherlock for my tabs which also connected to fragments.

我的问题是,当我要旋转屏幕时(即从纵向到横向,反之亦然),将再次调用我的活动,因此它将重新开始活动。

My Problem is when I am going to rotate the screen (that is portrait to landscape/vice-versa), my activity will be called again so it restarts my activity.

我不想重启我的活动,而只是恢复旋转之前显示的当前片段。请不要回答 android:configChanges = orientation | keyboardHidden ,因为它不能解决问题,但就像一个简单的技巧。我的解决方案是OnsaveInstanceState和onRestoreInstanceState方法,但我只是不知道如何在遇到问题时使用它。请帮我这个。

I want not to restart my activity but just restore the current fragment that was shown before it was rotate. PLEASE don't answer android:configChanges="orientation|keyboardHidden" since it does not solved the issue but just like a simple hack of it. My solution was the OnsaveInstanceState and onRestoreInstanceState Methods but I just don't know how to use it with my problem. Please help me with this one. Any response are highly much appreciated.

CODE:

 public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ActionBar actionBar = getSupportActionBar();  
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ActionBar.Tab tabA = actionBar.newTab().setIcon(R.drawable.about);
    ActionBar.Tab tabE = actionBar.newTab().setIcon(R.drawable.faq);
    ActionBar.Tab tabB = actionBar.newTab().setIcon(R.drawable.sponsors);
    ActionBar.Tab tabC = actionBar.newTab().setIcon(R.drawable.map);
    ActionBar.Tab tabD = actionBar.newTab().setIcon(R.drawable.destination);
    Fragment aboutTab = new PhotosActivity();
    Fragment sponsorTab = new SongsActivity();
    Fragment mapTab = new HCCMapActivity(); 
    Fragment questTab = new FaqActivity(); 
    Fragment DestinationTab = new TourActivity();
    tabA.setTabListener(new MyTabsListener(aboutTab));
    tabB.setTabListener(new MyTabsListener(sponsorTab));
    tabC.setTabListener(new MyTabsListener(mapTab));
    tabD.setTabListener(new MyTabsListener(DestinationTab));
    tabE.setTabListener(new MyTabsListener(questTab));
    actionBar.addTab(tabD, 0, true);
    actionBar.addTab(tabC, 1, false);
    actionBar.addTab(tabA, 2, false);
    actionBar.addTab(tabB, 3, false);
    actionBar.addTab(tabE, 4, false);
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putString("MyString", "Welcome back to Android");
  //savedInstanceState.putString("id",)
  // etc.
  //getSupportFragmentManager().putFragment(savedInstanceState, "fragment", getSupportFragmentManager().findFragmentById(R.id.fragment_place));
}


@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    FragmentManager fragmentManager ;
    FragmentTransaction ft ;
    super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  String myString = savedInstanceState.getString("MyString");
  Log.i("Hello", myString);

    fragmentManager =  getSupportFragmentManager();
    ft = fragmentManager.beginTransaction();
    ft.setCustomAnimations(R.anim.slide_out_left, R.anim.slide_out_right);  
    ft.replace(R.id.fragment_place, getSupportFragmentManager().getFragment(savedInstanceState, "fragment"), null); 
}

@Override
public void onConfigurationChanged (Configuration newConfig){
    Log.i("hello", "Config");
    super.onConfigurationChanged(newConfig); 
}

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    //MenuItem menuitem1 = menu.findItem(R.id.menuitem1);
    //menuitem1.setVisible(false);

    menu.getItem(1).setVisible(false);
    menu.getItem(0).setVisible(false);
    return true;
}


 protected class MyTabsListener implements TabListener{

    Fragment fragment;

    public MyTabsListener(Fragment fragment){

        this.fragment = fragment;
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {           
        if (myTabPosition < 0){
            //ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);  
        }else{
            if (myTabPosition >  tab.getPosition()){
                ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);   
            }else{
                ft.setCustomAnimations(R.anim.slide_out_left, R.anim.slide_out_right);  
            }
        }   
        myTabPosition = tab.getPosition();
        ft.replace(R.id.fragment_place, fragment, null);    
        //ft.commit();
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        ft.remove(fragment);
        getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }
}


推荐答案

默认情况下,设备旋转后将还原片段您无需再次添加它们。如果希望片段看起来相同,则应在片段本身中执行 onSaveInstanceState 。在活动中,您可以执行以下操作:

Fragments will be restored after a device rotation by default if you don't add them again. If you want the fragments to look the same then you should perform your onSaveInstanceState in the Fragment itself. In the Activity you could just do something like:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) {
        /* First launch, add fragments */
    } else {
        /* 
           Activity restored, don't add new fragments or in your case,
           don't make the first tab selected. 
        */
    }
}

即使您没有t在活动中覆盖 onSaveInstanceState 时,恢复 savedInstanceState 参数仍为非空>活动。只是一个空的 Bundle

Even if you don't override onSaveInstanceState in the activity, the savedInstanceState parameter will still be non-null when restoring an Activity. It'll just be an empty Bundle.

另一种选择是存储选定的选项卡索引是什么并在恢复活动后重新选择该选项卡。

Another option would be to store out what the selected tab index is and re-select that tab when your activity is restored.

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putInt("CurrentTab", currentTabIndex);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* Your existing code */

    if(savedInstanceState != null) {
        int currentTab = savedInstanceState.getInt("CurrentTab", 0);
        /* Set currently selected tab */
    }
}

这将重新选择当前选项卡,并显示正在显示的 Fragment 。唯一的缺点是您的片段状态未保存。要保存片段的状态,您必须执行第一个解决方案。

This would re-select the current tab and show the Fragment that was being shown. The only downside to this is that your fragment's state isn't saved. To save the fragment's state, you'd have to do something like the first solution.

这篇关于获取当前片段并保存在onSaveInstanceState()方法上以进行屏幕定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆