Android Fragment用法详解(2)--动态添加Fragment

时间:2023-03-08 15:52:22

在上一篇文章《Android Fragment用法详解(1)--静态使用Fragment》我们讲解了Fragment的最简单的用法。这次我们来说一说Fragment复杂一丢丢的用法。在代码中动态添加Fragment,让其实现类似微信主页面效果。也就是点击底部的按钮来动态改变中间内容页面。我们先来看看效果图吧。说明一下,为了方便大家复制粘贴,里面没有任何图片素材,都是用颜色和安卓自带图片来现实效果,所以有点难看哈~~毕竟我们是程序员不是美工嘛!

Android Fragment用法详解(2)--动态添加Fragment

接下来就是源代码啦

先看MainActivity的布局文件吧。因为布局文件是关键哦。

<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"
android:orientation="vertical" > <!-- 把Fragment当作普通控件使用,这里没啥作用,就是作为一个标题栏,不用Fragment,直接写布局一样的 -->
<fragment
android:id="@+id/fg_title"
android:name="com.example.fragmentdemo.TitleFragment"
android:layout_width="match_parent"
android:layout_height="45dp" /> <!-- 用一个帧布局来占一个位置,目的是给fragment用 -->
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</FrameLayout> <!-- 底部三个按钮,我们用RadioGroup来实现 -->
<include layout="@layout/bar" /> </LinearLayout>

然后看看底部四个按钮的布局吧

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/rg"
android:orientation="horizontal" > <!-- android:paddingLeft="0dp"加这个是为了让内容能够剧中 -->
<RadioButton
android:id="@+id/rb_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/bar_selector"
android:button="@null"
android:drawableTop="@android:drawable/star_on"
android:gravity="center"
android:paddingLeft="0dp"
android:text="Frag_1" /> <RadioButton
android:id="@+id/rb_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/bar_selector"
android:button="@null"
android:drawableTop="@android:drawable/star_on"
android:gravity="center"
android:paddingLeft="0dp"
android:text="Frag_2" /> <RadioButton
android:id="@+id/rb_3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/bar_selector"
android:button="@null"
android:drawableTop="@android:drawable/star_on"
android:gravity="center"
android:paddingLeft="0dp"
android:text="Frag_3" /> </RadioGroup>

然后就是三个按钮的选择器(就是控制点击底部按钮的时候,底部按钮能够变化背景颜色的选择器)

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:drawable="@android:color/holo_red_light" ></item>
<item android:state_checked="false" android:drawable="@android:color/holo_blue_bright"></item>
</selector>

接下来就是先上一些无关紧要的文件,哈哈。标题栏的类文件和布局文件

先看布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:background="#00ff00" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment制作的标题栏"
android:textColor="@android:color/black"
android:textSize="18sp" /> </RelativeLayout>

然后是类文件

package com.example.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
***************************************************************
*
* @版权 LinFeng
*
* @作者 LinFeng
*
* @版本 1.0
*
* @创建日期 2016-6-6
*
* @功能描述 用Fragment制作标题栏
*****************************************************************
*/
public class TitleFragment extends Fragment{ @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/**
* 加载布局文件然后返回view,显示在Activity
*/
View view = inflater.inflate(R.layout.title, container,false);
return view;
} }

然后就是重量级别的MainActivity类文件了

package com.example.fragmentdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup; public class MainActivity extends FragmentActivity implements OnClickListener { private RadioButton rb1;
private RadioButton rb2;
private RadioButton rb3; private RadioGroup rGroup; private Fragment f1,f2,f3;
private FragmentManager manager;
private FragmentTransaction transaction; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main); /**
* 拿到事务管理器并开启事务
*/
manager = getSupportFragmentManager();
transaction = manager.beginTransaction(); /**
* 初始化按钮
*/
rb1 = (RadioButton) findViewById(R.id.rb_1);
rb2 = (RadioButton) findViewById(R.id.rb_2);
rb3 = (RadioButton) findViewById(R.id.rb_3); rGroup = (RadioGroup) findViewById(R.id.rg); /**
* 为三个按钮添加监听
*/
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this); /**
* 启动默认选中第一个
*/
rGroup.check(R.id.rb_1);
f1 = new Fragment1();
transaction.replace(R.id.fl_content, f1);
transaction.commit();
} @Override
public void onClick(View v) { manager = getSupportFragmentManager();
transaction = manager.beginTransaction(); switch (v.getId()) {
case R.id.rb_1 :
/**
* 为了防止重叠,需要点击之前先移除其他Fragment
*/
hideFragment(transaction);
f1 = new Fragment1();
transaction.replace(R.id.fl_content, f1);
transaction.commit(); break;
case R.id.rb_2 :
hideFragment(transaction);
f2 = new Fragment2();
transaction.replace(R.id.fl_content, f2);
transaction.commit(); break;
case R.id.rb_3 :
hideFragment(transaction);
f3 = new Fragment3();
transaction.replace(R.id.fl_content, f3);
transaction.commit();
break; default :
break;
}
} /*
* 去除(隐藏)所有的Fragment
* */
private void hideFragment(FragmentTransaction transaction) {
if (f1 != null) {
//transaction.hide(f1);隐藏方法也可以实现同样的效果,不过我一般使用去除
transaction.remove(f1);
}
if (f2 != null) {
//transaction.hide(f2);
transaction.remove(f2);
}
if (f3 != null) {
//transaction.hide(f3);
transaction.remove(f3);
} } }

到这里基本都结束了。哈哈,然后聪明的同学一定还注意到MainActivtiy里还有3个Fragment的类,由于这三个基本是99%相同的,所以我就贴出其中一个的代码(其他两个无非就是修改显示文字,类文件名而已~~其他全部相同)

先看类文件

package com.example.fragmentdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
***************************************************************
*
* @版权 LinFeng
*
* @作者 LinFeng
*
* @版本 1.0
*
* @创建日期 2016-6-6
*
* @功能描述
*****************************************************************
*/ /**
* 这里要注意,Fragment是要引入android.support.v4.app.Fragment这个包里面的,不是那个app.fragment那个包哦
* @author LinFeng
*
*/
public class Fragment1 extends Fragment{ @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frament1, container,false);
return 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:background="#ffff00"
android:gravity="center"
android:orientation="vertical" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:text="FRAGMENT_1" /> </LinearLayout>

看到这里,相信大家基本都学会动态添加Fragment了吧!为什么不直接贴出项目代码给大家下载?主要是,我不建议大家直接下载人家的项目来运行,然后阅读,感觉你会了。但其实,如果自己写,可能会出现各种奇葩的问题,所以,根据人家的思路,自己写一遍,运行一下,出来的,才是你自己的。

《==================================这是一条华丽的分割线================================》

最后我们看一些关于Fragment的东西,刚刚好在人家的博客里面看到觉得不错就COPY过来给大家看看了。

a、获取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//开启一个事务

transaction.add() 

往Activity中添加一个Fragment

transaction.remove()

从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁。

transaction.replace()

使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体~

transaction.hide()

隐藏当前的Fragment,仅仅是设为不可见,并不会销毁

transaction.show()

显示之前隐藏的Fragment

detach()

会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护。

attach()

重建view视图,附加到UI上并显示。

transatcion.commit()//提交一个事务

注意:常用Fragment的哥们,可能会经常遇到这样Activity状态不一致:State loss这样的错误。主要是因为:commit方法一定要在Activity.onSaveInstance()之前调用。

上述,基本是操作Fragment的所有的方式了,在一个事务开启到提交可以进行多个的添加、移除、替换等操作。

值得注意的是:如果你喜欢使用Fragment,一定要清楚这些方法,哪个会销毁视图,哪个会销毁实例,哪个仅仅只是隐藏,这样才能更好的使用它们。

a、比如:我在FragmentA中的EditText填了一些数据,当切换到FragmentB时,如果希望会到A还能看到数据,则适合你的就是hide和show;也就是说,希望保留用户操作的面板,你可以使用hide和show,当然了不要使劲在那new实例,进行下非null判断。

b、再比如:我不希望保留用户操作,你可以使用remove(),然后add();或者使用replace()这个和remove,add是相同的效果。

c、remove和detach有一点细微的区别,在不考虑回退栈的情况下,remove会销毁整个Fragment实例,而detach则只是销毁其视图结构,实例并不会被销毁。那么二者怎么取舍使用呢?如果你的当前Activity一直存在,那么在不希望保留用户操作的时候,你可以优先使用detach。