基于fragment的页面切换功能

来源:互联网 发布:最悲惨的人生 知乎 编辑:程序博客网 时间:2024/05/19 19:41

Fragment(完全依赖于Activity)
首先,需要建一个主的Activity文件,主要继承FragmentActivity类,实现OnPageChangeListener和OnClickListener接口。
然后,创建一个list的对象fragments。
a. 利用fragment和listView写带导航的页面跳转

底部的按钮是在RadioGroup中添加RadioButton实现的,

<EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/editText3"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:hint="请输入电影的名字"/><ListViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/LV"android:layout_alignParentLeft="true"android:layout_alignParentStart="trueandroid:layout_below="@+id/editText3">

public class denglus extends FragmentActivity implements OnPageChangeListener,OnClickListener {
private List fragments=new ArrayList<>();
private ViewPager vp;
private RadioButton dy,yy,fx,wo;

protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_denglus);    dy=(RadioButton)findViewById(R.id.radioButton);    yy=(RadioButton)findViewById(R.id.radioButton2);    fx=(RadioButton)findViewById(R.id.radioButton3);    wo=(RadioButton)findViewById(R.id.radioButton4);    dy.setOnClickListener(this);    yy.setOnClickListener(this);    fx.setOnClickListener(this);    wo.setOnClickListener(this);    vp=(ViewPager)findViewById(R.id.vp);    vp.setOnPageChangeListener(this);    IndexFragment idf=new IndexFragment();    yyFragment yf=new yyFragment();    fxFragment fxf=new fxFragment();    woFragment wf=new woFragment();    fragments.add(idf);    fragments.add(yf);    fragments.add(fxf);    fragments.add(wf);    ViewPagerAdapter vpa=new ViewPagerAdapter(getSupportFragmentManager(),fragments);    vp.setAdapter(vpa);}

b.切换页面的位置主要由下的代码实现。

<android.support.v4.view.ViewPager        android:id="@+id/vp"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"></android.support.v4.view.ViewPager>

c.每一个按钮与一个Fragment相连

dy=(RadioButton)findViewById(R.id.radioButton);
yy=(RadioButton)findViewById(R.id.radioButton2);
fx=(RadioButton)findViewById(R.id.radioButton3);
wo=(RadioButton)findViewById(R.id.radioButton4);

    dy.setOnClickListener(this);    yy.setOnClickListener(this);    fx.setOnClickListener(this);    wo.setOnClickListener(this);    vp=(ViewPager)findViewById(R.id.vp);    vp.setOnPageChangeListener(this);    IndexFragment idf=new IndexFragment();    yyFragment yf=new yyFragment();    fxFragment fxf=new fxFragment();    woFragment wf=new woFragment();    fragments.add(idf);    fragments.add(yf);    fragments.add(fxf);    fragments.add(wf);
0 0
原创粉丝点击