gpt4 book ai didi

android - 使用 Fragment Pager Adapter 启动时的默认 fragment

转载 作者:行者123 更新时间:2023-11-29 17:26:22 33 4
gpt4 key购买 nike

我正在使用 android studio 提供的默认模板来创建带有 fragment 的选项卡式 Activity 。一切正常。我有 2 个选项卡,一个用于 wifi,另一个用于移动网络。我想做的是在应用程序启动时检查用户是否连接到 wifi 或移动网络。如果 wifi 将他直接导航到 wifi 选项卡,反之亦然。我尝试使用连接管理器来检测 netwotk 连接,但无法正确切换选项卡。我没有找到正确的位置以及我应该如何更改标签页

public class MainActivity extends AppCompatActivity {

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

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
title= (TextView) findViewById(R.id.toolbar_title);
Fonts.setMonthoersFont(this,title);

SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);



}


/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {

public SectionsPagerAdapter(FragmentManager fm) {
super(fm);

}
@Override
public Fragment getItem(int position) {
switch (position) {

case 0:
return FragmentWifi.newInstance(0);
case 1:
return FragmentMobileNetworks.newInstance(1);
default:
return new Fragment();
}

// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//
}

@Override
public int getCount() {
// Show 3 total pages.
return 2;
}

@Override
public CharSequence getPageTitle(int position) {

switch (position) {
case 0:
return "Wi-Fi";
case 1:
return "Mobile Network";
}
return null;
}
}

最佳答案

试试这个

    ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);


final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnectedOrConnecting ()) {
mViewPager.setCurrentItem(0);
} else if (mobile.isConnectedOrConnecting ()) {
mViewPager.setCurrentItem(1);
} else {
Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show();
}

关于android - 使用 Fragment Pager Adapter 启动时的默认 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409538/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com