Fragment的用法
2017-01-09 21:59
543 查看
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。
相关文章推荐
- Android中Fragment的解析和使用详解
- Android Activity与Fragment实现底部导航器
- Android用Fragment创建选项卡
- Android中fragment与activity之间的交互(两种实现方式)
- Android Fragment 基本了解(图文介绍)
- Android程序开发之Fragment实现底部导航栏实例代码
- Android开发 Activity和Fragment详解
- Android应用开发中Fragment与Activity间通信示例讲解
- Android的Fragment的生命周期各状态和回调函数使用
- 浅谈Android App开发中Fragment的创建与生命周期
- 实例探究Android开发中Fragment状态的保存与恢复方法
- Android Fragment的使用方法(翻译)
- Android开发技巧之Fragment的懒加载
- 实例探究Android应用编写时Fragment的生命周期问题
- Android App开发中创建Fragment组件的教程
- Android Fragment+FragmentTabHost组件实现常见主页面(仿微信新浪)
- Android Fragment多层嵌套重影问题的解决方法
- 详解Android中fragment和viewpager的那点事儿
- Android中的Fragment类使用进阶
- 使用Fragment来处理Andoird app的UI布局的实例分享