我遇到了一个小问题。我正在为我的Android开发课程构建一个应用程序,我有两个活动 - MainActivity和带有三个片段布局的片段活动。我设法编写代码,当您单击MainActivity中的按钮时,它会将您带到第二个片段活动。这很好用但是当我单击后退按钮时它会关闭应用程序而不是返回主要活动布局。这是一些代码:
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
getSecondAct();
}
public void getSecondAct(){
Button btnstart = (Button) findViewById(R.id.btnfragments);
btnstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent1 = new Intent(MainActivity.this,
FragmentsActivity.class);
startActivity(intent1);
}
});
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Thank you for using this app! :)",
Toast.LENGTH_SHORT).show();
finish();
}
}
FragmentsActivity:
public class FragmentsActivity extends AppCompatActivity {
private FragmentsAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new FragmentsAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragments, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FragmentsAdapter:
public class FragmentsAdapter extends FragmentPagerAdapter {
public FragmentsAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) { //position ide od nule!
return RollDiceFragment.newInstance();
} else if (position == 1) {
return FAEFragment.newInstance();
} else if (position == 2) {
return FateCoreFragment.newInstance();
} else {
return null;
}
}
@Override
public int getCount() {
return 3;
}
}
片段本身还没有任何特定的代码,因为我还没有进入布局。我正在使用选项卡式活动在三个片段之间切换,我不知道为什么应用程序关闭而不是返回到MainActivity屏幕。
答案 0 :(得分:0)
您应该从主要活动中删除停止方法
答案 1 :(得分:0)
您在finish()
方法上调用了onStop
,这会导致您的启动器活动失效。请删除该代码,然后您就可以了。