我想从空活动切换到选项卡式布局活动。我使用了意图,但它不起作用,应用程序不断崩溃。 我在我的主要活动中使用了一个按钮,我想跳转到名为选项卡式活动的LeaderBoards。怎么做?
主要活动中的此按钮:
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(game4x4.this, LeaderBoards.class);//game4x4 is the main activity
startActivity(intent);
}
});
选项卡式活动类:
public class LeaderBoards extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
int page=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leader_boards);
viewPager=(ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(),getApplicationContext()));
viewPager.setCurrentItem(page);
tabLayout=(TabLayout)findViewById(R.id.tablayout);
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());
}
});
}
private class CustomAdapter extends FragmentPagerAdapter
{
private String fragments[]= {"MyScore","TopScores"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext)
{
super(supportFragmentManager);
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
return null;
}
}
@Override
public int getCount() {
return fragments.length;
}
@Override
public CharSequence getPageTitle(int position)
{
return fragments[position];
}
}
}
Fragemt1和Fragment2是不同标签的类。
答案 0 :(得分:0)
尝试这种方式
viewPager=(ViewPager)findViewById(R.id.viewpager);
tabLayout=(TabLayout)findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(),getApplicationContext()));
viewPager.setCurrentItem(page);
答案 1 :(得分:0)
检查" LeaderBoards"是否在清单中提及。