Fragment的用法

来源:互联网 发布:大数据相关技术 编辑:程序博客网 时间:2024/06/05 04:13

Fragment的用法

  • 当我们需要在一个activity里切换不同的界面时,切换界面可以设置为切换不同的fragment.

代码详解

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout         android:layout_width="wrap_content"        android:layout_height="match_parent"        android:orientation="vertical"        >        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="click1"            android:text="fragment1"            />        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="click2"            android:text="fragment2"            />        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="click3"            android:text="fragment3"            />    </LinearLayout>    <FrameLayout         android:id="@+id/fl"        android:layout_weight="1"        android:layout_width="0dp"        android:layout_height="match_parent"        ></FrameLayout></LinearLayout>

  • 我们给main_activity上图所示的布局,左边一栏是不同的button用于切换不同的fragment,右边空白的是帧布局framelayout,用于显示fragment。

     public void click1(View v){        Fragment1 fragment1 = new Fragment1();        FragmentManager fm = getFragmentManager();        FragmentTransaction ft = fm.beginTransaction();        ft.replace(R.id.fl, fragment1);        ft.commit();    }
  • 在点击按钮后,首先需要new出一个fragment对象。然后通过FragmentManager获取到FragmentTransaction,然后通过它来将fragment对象替换到activity布局下的帧布局(framelayout)上。

    public class Fragment1 extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment1, null);        return view;    }}
  • 在Fragment1类中我们需要实现onCreateView()方法,这个方法和activity的setContentView类似,需要对当前的fragment设置布局文件,然后返回这个view对象。

    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"     android:background="#f00"    >    <TextView         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="第一个fragment"        android:textSize="20sp"        android:gravity="center_horizontal"        /></LinearLayout>
  • 这是R.layout.fragment1的代码,用于简单的指示不同的fragment。

0 0
原创粉丝点击