我正在使用android studio提供的默认模板来创建带有片段的标签活动。每件事情都很好。我有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;
}
}
}
答案 0 :(得分:2)
试试这个
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();
}
答案 1 :(得分:0)
在你的Activity / Fragment中,一旦PagerAdapter附加到寻呼机,(确保已经调用onResume of activity,检查网络状态并调用它):
if(isConnectedWithWifi){
mViewPager.setCurrentItem(_POSITION_OF_FRAGMENT_WH);
}