我的 viewpager 运行良好,当我单击视图/页面时,它会打开一个新活动,但是当我想按返回以转到 viewpager 时,应用程序会关闭。当我按下后退按钮时,如何让 viewpager 正确打开到当前页面?
我知道这是应该的,所以这里是 viewpager 代码:
public class LogoQuizActivity extends Activity {
private
class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
//Log.i(TAG, "page selected " + position);
currentPage = position;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(currentPage);
myPager.setPadding(0, 150, 0, 0);
PageListener pageListener = new PageListener();
myPager.setOnPageChangeListener(pageListener);
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null; // this comes first
int resId = 0;
switch (position) {
case 0:
resId = R.layout.farleft;
view = inflater.inflate(resId, null);
break;
case 1:
resId = R.layout.left;
view = inflater.inflate(resId, null);
break;
case 2:
resId = R.layout.middle;
view = inflater.inflate(resId, null);
break;
case 3:
resId = R.layout.right;
view = inflater.inflate(resId, null);
break;
case 4:
resId = R.layout.farright;
view = inflater.inflate(resId, null);
break;
}
view.setTag(position);
view.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
int position = (Integer) view.getTag();
Log.v("Log_tag", "Here image is clicked" + position);
if(position == 0){
Intent intent = new Intent(LogoQuizActivity.this,
LevelOne.class);
startActivity(intent);
}
if(position == 1){
Intent intent = new Intent(getBaseContext(),
LevelTwo.class);
startActivity(intent);
}
if(position == 2){
Intent intent = new Intent(getBaseContext(),
LevelThree.class);
startActivity(intent);
}
if(position == 3){
Intent intent = new Intent(getBaseContext(),
LevelFour.class);
startActivity(intent);
}
if(position == 4){
Intent intent = new Intent(getBaseContext(),
LevelFive.class);
startActivity(intent);
}
}
});
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
@Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
@Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
}
}
我不确定这是否与恢复状态方法有关或在 parcelable savestate 中返回 null。这可能是完全显而易见的,所以提前感谢!