您的位置:首页 > 其它

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

2015-09-22 22:35 357 查看
今天介绍一下碎片结合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啦。任务完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: