【发布时间】:2015-08-04 12:36:13
【问题描述】:
我的活动片段 1 和片段 2 中有两个片段,我希望当用户单击片段 2 中的后退按钮时,它应该将用户导航到片段 1
我的活动xml代码是:我在xml中设置片段
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Routeplan" >
<FrameLayout
android:id="@+id/content_frame_polymer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<viewpager.helper.JazzyViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
我的活动代码:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.packing_activity);
mPager = (JazzyViewPager)findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager(),NUM_PAGES,mPager);
mPager.setAdapter(padapter);
mPager.setPageMargin(30);
}
}
PagerAdapter 代码:
public class PagerAdapter extends FragmentPagerAdapter {
int NUM_PAGES;
JazzyViewPager mPager;
public PagerAdapter(FragmentManager fm, int numPages, JazzyViewPager mPager) {
super(fm);
this.NUM_PAGES=numPages;
this.mPager=mPager;
// TODO Auto-generated constructor stub
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
mPager.setObjectForPosition(obj, position);
return obj;
}
@Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new Fragmentone();
case 1:
return new Fragmenttwo();
default:
break;
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUM_PAGES;
}
}
分片代码:
public class FragmentOne extends Fragment {
private ViewGroup rootView1;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return rootView1 = (ViewGroup) inflater
.inflate(R.layout.about_rohtak, container, false);
}
}
片段二代码:
public class FragmentTwo extends Fragment {
private ViewGroup rootView1;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return rootView1 = (ViewGroup) inflater
.inflate(R.layout.about_rohtak, container, false);
}
}
【问题讨论】:
-
1) 在活动中覆盖 onBackPressed 2) 使用 getCurrentItem() 检查寻呼机的当前位置 3) 如果位置为 1,则使用 setCurrentItem(int item) 将当前项设置为 0 4) 否则完成活动
-
@Karn shah 谢谢。它对我有用
-
欢迎您。如果它对你有用,请投票赞成评论。
标签: android android-fragments fragment