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
- Android fragment的用法
- fragment的用法笔记
- -----fragment的用法
- fragment的用法笔记
- fragment的用法笔记
- Fragment的用法
- Fragment的部分用法
- Fragment的简单用法
- 关于Fragment的用法
- Fragment的用法
- Fragment的用法简介
- Fragment的用法
- Fragment的初步用法
- fragment的基本用法
- Fragment的简单用法
- fragment回退栈的用法
- Fragment的用法
- fragment 的简单用法
- 数据挖掘中的时序数据分析方法(According to Eamonn Keogh’s Time Series Tutorial)
- 1078. Hashing (25)
- sevureCRT乱码
- 24. Swap Nodes in Pairs
- JavaScript判断对象数组是否包含对象
- Fragment的用法
- GIT远程仓库基本操作(1)
- 命令模式c++实现
- 深入浅出Mybatis-改造Cache
- 异常Throwable(Exception/Error)
- JVM内存管理之内存结构
- Install CM13 ROM on Huawei Honor 5X
- 判断单链表中是否有环的问题
- Hashtable和HashMap的异同