自学安卓复习基础_之十一(在Activity中加载fragment的页面)

今天介绍一下碎片结合activity的简单用法(在一个activity中添加两个碎片)
步骤一:新建碎片布局left_fragment.xml
页面很简单就一个button按钮在布局里
步骤二:新建碎片布局right_fragment.xml
页面也很简单,就一个TextView
步骤三:新建LeftFragement类指定布局left_fragment.xml


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;
    }
}

这里要注意了Fragment是Android3.0之后引进的,所以他就要求sdk最低版本是11.
步骤四:新建RightFragement类指定布局right_fragment.xml

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;
    }
}

步骤五:然后修改main.xml

<?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="horizontal" >
    <!-- 此处注意了,必须给fragment指定id 不然运行时会报异常奔溃 -->

    <fragment 
        android:id="@+id/lef"
        android:name="com.example.testfragment.fragment.LeftFragment"
        android:layout_width="0dp"
          android:layout_height="match_parent"
        android:layout_weight="1"
        />
    <fragment 
        android:id="@+id/right"
        android:name="com.example.testfragment.fragment.RightFragment"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        />

</LinearLayout>

在MainActivity中无需操作什么,就只用setContentView(R.layout.main)。ok啦。任务完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值