在我的应用程序中,当我按下以下活动的后退按钮时,不会返回主要活动(片段)但应用程序关闭。
public class ListaSmartphone extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_smartphone);
Button buttonSP = (Button)findViewById(R.id.buttonXIAOMI);
buttonSP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent openListaSP = new Intent(ListaSmartphone.this, ElencoXiaomi.class);
startActivity(openListaSP);
}
});
Button buttonTB = (Button)findViewById(R.id.buttonMEIZU);
buttonTB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent openListaTB = new Intent(ListaSmartphone.this, ElencoMeizu.class);
startActivity(openListaTB);
}
});
}
}
这是主要的活动代码
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
vpPager.setPageTransformer(true, new RotateUpTransformer());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static final String[] TAB_TITLES = new String[]{"WOW STORE", "PRODOTTI", "SERVIZI", "INFO"};
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentWithZeroImage.newInstance("", R.drawable.wowstorelogo);
case 1:
return FragmentWithOneImage.newInstance("", R.drawable.prodotti);
case 2:
return FragmentWithTwoImages.newInstance("", R.drawable.riparazioni);
case 3:
return FragmentWithThreeImages.newInstance("", R.drawable.info);
default:
return null;
}
}
@Override
public int getCount(){
return TAB_TITLES.length;
}
@Override
public CharSequence getPageTitle(int position){
return TAB_TITLES[position];
}
}
}
应用程序工作正常,没有错误,但在按下后退按钮的设备上,应用程序退出并且不会返回到MainActivity。 我使用Main Activity和四个片段。
答案 0 :(得分:0)
在传递意图时你可能使用了finish();在startActivity()
之后答案 1 :(得分:0)
使用此代码:
@Override
public void onBackPressed() {
this.startActivity(new Intent(ListaSmartphone.this,MainActivity.class));
// super.onBackPressed();
}
并在MainActivity的onCreate
函数中打开片段
答案 2 :(得分:0)
如果您想返回按返回按钮上的MainActivity,请使用此代码
@Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}