android – 如何使用选项卡设置多个滑动视图的默认选项卡?

前端之家收集整理的这篇文章主要介绍了android – 如何使用选项卡设置多个滑动视图的默认选项卡?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我真的被卡住了.我在我的主要活动中使用选项卡进行了四次滑动视图,但我想要的是当用户打开应用程序时,它会自动显示第二个选项卡而不是第一个选项卡.

这是我的MainActivity.java

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "First Tab","Second Tab","Third Tab","Fourth Tab" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0,float arg1,int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab,FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab,FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab,FragmentTransaction ft) {
}

这是我的main_activity.xml:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">

</android.support.v4.view.ViewPager>

解决方法

第二个选项卡是索引1,您需要做的就是在设置页面更改侦听器后添加setCurrentItem以将当前选项卡更改为正确的选项卡.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_paged);

    ... code omitted ...

    /**
     * on swiping the viewpager make respective tab selected
     **/
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {...}

    // set the default tab to the second tab   
    viewPager.setCurrentItem(1,false);
}
原文链接:https://www.f2er.com/android/312310.html

猜你在找的Android相关文章