我已经实现了一个viewpager并且它工作正常,但是当使用BACK按钮时它不会被关闭,并且使用默认fragent再次加载viewpager,然后如果我再次按下按钮它终于完成了。我设置Back Button时的行为与super.onBackPressed()相同;或者在viewpager中逐个片段地返回。希望您能够帮助我。我的代码
Viewpager活动
public class PerfilSlideActivity extends FragmentActivity {
private static final int NUM_PAGES = 3;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpagerindicator);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
/*
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}*/
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Mi_perfil();
case 1:
return new Mi_porfil2();
case 2:
return new Mi_perfil3();
default: return new Mi_perfil();
}
}
@Override
public int getCount() {
return NUM_PAGES;
}
}
}
我的xml幻灯片
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
我使用的是3个碎片中的一个,其他的是相同的
public class Mi_perfil extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mi_perfil, container, false);
return rootView;
}
}
为了完成,我使用Intent从其他活动打开另一个Fragment的ViewPager活动:
public boolean onTouch(View v, MotionEvent event) {
spPerfiles = new SharedPreferenceSurveyTemp(getActivity());
Intent i=new Intent(getActivity(),ScreenSlideActivity.class);
startActivity(i);
return true;
}
答案 0 :(得分:0)
你应该完成:
Intent i=new Intent(getActivity(),ScreenSlideActivity.class);
startActivity(i);
finish();
如果这不起作用,请尝试使用FragmentTransaction / FragmentManager传递片段。
答案 1 :(得分:0)
问题是尝试使用OnTouchListener
在片段中打开新活动。这不是正确的方法,并且导致我的活动多次打开。
我通过实现OnClickListener
来修复此问题:
public boolean onClick(View v) {
Intent i=new Intent(getActivity(),ScreenSlideActivity.class);
startActivity(i);
}