Fragment简单用法

一.示意图

 

 

二.新建一个左侧碎片布局left_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#ffff00">

 

 

    <Button

        android:text="加载内容"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/btn"

        android:layout_weight="1"

        android:onClick="myClick"/>

</LinearLayout>

 

 

三.创建左侧碎片类LeftFragment.java:

注意:这里可能会有两个不同包下的Fragment 供你选择,建议使用android.app.Fragment,因为我们的程序是面向Android 4.0 以上系统的,另一个包下的Fragment 主要是用于兼容低版本的Android系统。

 

public class LeftFragment extends Fragment {

           @Override

           public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

              View view = inflater.inflate(R.layout.left_fragment, container, false);

              return view;

           }

}

 

 

四.新建一个右侧碎片布局right_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#0000ff">

 

    <TextView

        android:text="TextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/textView2"

        android:layout_weight="1" />

</LinearLayout>

 

 

五.新建右侧碎片类RightFragment.java:

public class RightFragment extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.right_fragment, container, false);

        return view;

    }

}

 

六.activity_main.xml布局

<?xml version="1.0" encoding="utf-8"?>

<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">

    <fragment

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:name="com.example.guo.fragment.LeftFragment"

        android:layout_weight="1"

        android:id="@+id/left_fragment" />

 

    <fragment

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:name="com.example.guo.fragment.RightFragment"

        android:layout_weight="1"

        android:id="@+id/right_fragment" />

</LinearLayout>

 

 

注意:对于fragment,在布局文件中,id是必须的,否则会报错

 

七.新建平板模拟器,运行即可

posted @ 2017-04-19 11:15  rorshach  阅读(332)  评论(0编辑  收藏  举报