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是必须的,否则会报错
七.新建平板模拟器,运行即可
相关文章
- Hilbert曲线简单介绍及生成算法
- 地球引擎初级教程——Google Earth Engine计算最简单的多边形面积和周长计算
- Delphi FDMemTable内存表用法及简单操作函数封装
- 并行编程简单用法及异常处理
- jquery中hover()的用法。简单粗暴
- 《Android游戏开发详解》一2.7 构建一个简单的计数程序
- 《R绘图系统(第2版)》一第2章 传统绘图系统的简单用法2.1 传统绘图模型
- ZOJ1760 Doubles (简单查找题)
- 超链接标签简单的几个样式属性
- 函数-memcpy有三种用法,第一种简单,另外两种非常巧妙,你知道吗?
- 响应式网页设计简单入门
- JavaScript-4.1-简单的表单操作,函数用法---ShinePans
- VC6 鼠标钩子 最简单样例
- 搭建React项目,超简单教程