简体   繁体   English

如何通过屏幕旋转存储分页器视图的状态

[英]how to store state of pager view with screen rotation

i want to add screen rotation support to the activity having a pager view. 我想为具有寻呼机视图的活动添加屏幕旋转支持。 what i want is when user changes screen orientation, the tab of pager view that was open should be opened in the new orientation. 我想要的是当用户更改屏幕方向时,应以新方向打开已打开的寻呼机视图的选项卡。 but now activity restarts and every time first tab opens. 但现在活动会重新启动,并且每次第一个标签打开。 kindly help me . 请帮我。 Thanks in Advance. 提前致谢。

package com.example.ali.namallibrary;
import android.app.Fragment;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.Serializable;

public class aboutLibrary extends AppCompatActivity {

CustomAdapter customAdapterpter = null;
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_library);
    customAdapterpter  = new CustomAdapter(getSupportFragmentManager(),getApplicationContext());

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(customAdapterpter);

    tabLayout = (TabLayout) findViewById(R.id.tabBar);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()   {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    });
} // end of oncreate

private class CustomAdapter extends FragmentPagerAdapter {
    private String[] fragmentNames = {"About","Collection","Timing","Contact"};
    public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
        super(supportFragmentManager);
    }
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch (position)
        {
            case 0 :
                return new aboutLibraryFrag();
            case 1 :
                return new libraryCollectionFrag();
            case 2 :
                return new libraryTimingFrag();
            case 3 :
                return new contactUsFrag();
            default:
                return null;
        }
    }
    @Override
    public int getCount() {
        return fragmentNames.length;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentNames[position];
    }
}

Another way to deal with screen changes and or rotation is to add android:configChanges to your activity: 处理屏幕更改和/或旋转的另一种方法是将android:configChanges添加到您的活动中:

<activity android:name="com.example.myactivity" 
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode" />

The ConfigChanges mentioned will not cause your activity to be detroyed and recreated when they occur instead, Android will simply rotate the screen and then call onConfigurationChanged where you can manually handle the cases yourself. 提及的ConfigChanges不会导致您的活动遭到破坏并被重新创建,Android只需旋转屏幕,然后调用onConfigurationChanged在此处手动处理案件。

You can override onConfigurationChanged in your activity to handle the events. 您可以在活动中覆盖onConfigurationChanged来处理事件。

public class myactivity extends Activity
{
    //..

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
}

Read more in the Android documentation here 此处阅读更多Android文档

Whenever your rotate the screen, the activity is completely destroyed and re-created. 每当旋转屏幕时,活动都会被完全破坏并重新创建。 To deal with this, there is a lifecycle method called onSaveInstanceState . 为了解决这个问题,有一个称为onSaveInstanceState的生命周期方法。 In this method you can save a Bundle object. 在这种方法中,您可以保存Bundle对象。 A Bundle is a bunch of key value pairs that you define, which you want around after the rotation. Bundle是您定义的一堆键值对,您需要在旋转后对其进行处理。 In that Bundle, you can store the current position of your view pager. 在该捆绑包中,您可以存储视图寻呼机的当前位置。 I'm haven't worked much with ViewPagers, but getCurrentItem might be what you're looking for. 我在ViewPagers方面工作不多,但是getCurrentItem可能正是您想要的。 You'd need to make your ViewPager a member variable, and a constant for the key. 您需要使ViewPager成为成员变量,并为键设置一个常量。 Then I'm guessing it would look something like: 然后,我猜它看起来像:

public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(CURRENT_POSITION_KEY, mViewPager.getCurrentItem());

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

The onCreate method takes a Bundle savedInstanceState - if the activity is being restarted from a rotation, this parameter will have everything you saved in onSaveInstanceState . onCreate方法使用Bundle savedInstanceState -如果Bundle savedInstanceState中重新启动活动,则此参数会将您保存的所有内容保存在onSaveInstanceState Thus you can do something like this in onCreate : 因此,您可以在onCreate

// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
 int currentPos = savedInstanceState.getInt(CURRENT_POSITION_KEY);
 mViewPager.setCurrentItem(currentPos)
}

More information about loading and saving the state between rotations can be found here: https://developer.android.com/guide/components/activities/activity-lifecycle.html#saras 有关在轮换之间加载和保存状态的更多信息,请参见以下网址https//developer.android.com/guide/components/activities/activity-lifecycle.html#saras

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

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