Android中Fragment的Hide和Show
我们都知道,Fragment动态添加的时候我们可以使用FragmentTransaction的add和replace方法,replace方法就等效于对这个Fragment先执行remove(),再执行add()。但是在实际的项目中,有很多时候我们会用到底部是一个RadioGroup包裹的RadioButton,上面用Fragment的情况,因为我们是从网络上获取的数据,这种时候我们不希望点击加载过的页面(也就是加载过的Fragment)的时候,每次都重新加载。也就是使用FragmentTransaction#replace()或者是add()方法行不通了,影响用户体验,这个时候就要用到FragmentTracsaction中的另两个方法了,也就是今天要提到的hide()和show()方法。这两个方法简单地说是会隐藏指定的Fragment,并不会销毁此Fragment,所以也就是可以保存下来之前在此Fragment中加载的数据了~。下面来看一下这个Demo吧:
我们要实现的就是这样一个效果:

其实不在网络上加载数据的话看不出来什么具体的效果,不过我们还是先看一下代码吧:
主页面的布局如下:
<?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"
> <LinearLayout
android:id="@+id/layout_main_fragment"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"> </LinearLayout> <RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentBottom="true"
android:orientation="horizontal"> <RadioButton
android:id="@+id/rb_tj"
android:layout_width="0dp"
android:layout_height="65dp"
android:layout_weight="1"
android:background="@drawable/rb_tuijian"
android:button="@null"
android:checked="true" /> <RadioButton
android:id="@+id/rb_sj"
android:layout_width="0dp"
android:layout_height="65dp"
android:layout_weight="1"
android:background="@drawable/rb_shujia"
android:button="@null" /> <RadioButton
android:id="@+id/rb_fl"
android:layout_width="0dp"
android:layout_height="65dp"
android:layout_weight="1"
android:background="@drawable/rb_fenlei"
android:button="@null" /> <RadioButton
android:id="@+id/rb_gd"
android:layout_width="0dp"
android:layout_height="65dp"
android:layout_weight="1"
android:background="@drawable/rb_gengduo"
android:button="@null" />
</RadioGroup>
</LinearLayout>
这里用到了四个selector选择器作为RadioButton的背景,其他的没有什么,很简单的布局。当然,为了展示,我们还需要一个Fragment以及其对应的布局:
<?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">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="@android:color/holo_red_light"
android:text="哈哈哈"/>
</LinearLayout>
由于只是一个小Demo,这里就没有写多个Fragment,而是复用了这一个Fragment,通过Fragment#setArgument(Bundle bundle)方法和getArgument()方法来复用该Fragment:
package ggcomic.rabbit.lx.fragmenthideandshow.fragment; import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import ggcomic.rabbit.lx.fragmenthideandshow.R; /**
* Created by Lx on 2016/9/20.
*/
public class MyFragment extends Fragment { private TextView tv; @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, null);
tv = (TextView) view.findViewById(R.id.tv);
Bundle bundle = getArguments();
int tag = bundle.getInt("tag");
switch (tag) {
case 1:
tv.setText("推荐");
break;
case 2:
tv.setText("书架");
break;
case 3:
tv.setText("分类");
break;
case 4:
tv.setText("更多");
break;
}
return view;
}
}
最主要的就是在MainActivity中的处理:
package ggcomic.rabbit.lx.fragmenthideandshow.main; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton; import ggcomic.rabbit.lx.fragmenthideandshow.R;
import ggcomic.rabbit.lx.fragmenthideandshow.fragment.MyFragment; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Fragment currentFragment=new Fragment();
private LinearLayout layout;
private RadioButton rb_tj,rb_sj,rb_fl, rb_gd;
private Fragment fragment_tj,fragment_sj,fragment_fl, fragment_gd;
private FragmentManager manager; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initFragment();
initEvent();
showFragment(fragment_tj);
} /**
* 初始化监听
*/
private void initEvent() {
rb_tj.setOnClickListener(this);
rb_sj.setOnClickListener(this);
rb_fl.setOnClickListener(this);
rb_gd.setOnClickListener(this);
} /**
* 初始化Fragment
*/
private void initFragment() {
manager = getSupportFragmentManager(); Bundle bundle = new Bundle();
bundle.putInt("tag", 1);
fragment_tj = new MyFragment();
fragment_tj.setArguments(bundle); bundle = new Bundle();
bundle.putInt("tag", 2);
fragment_sj = new MyFragment();
fragment_sj.setArguments(bundle); bundle = new Bundle();
bundle.putInt("tag", 3);
fragment_fl = new MyFragment();
fragment_fl.setArguments(bundle); bundle = new Bundle();
bundle.putInt("tag", 4);
fragment_gd = new MyFragment();
fragment_gd.setArguments(bundle);
} /**
* 展示Fragment
*/
private void showFragment(Fragment fragment) {
if (currentFragment!=fragment) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(currentFragment);
currentFragment = fragment;
if (!fragment.isAdded()) {
transaction.add(R.id.layout_main_fragment, fragment).show(fragment).commit();
} else {
transaction.show(fragment).commit();
}
}
} /**
* 初始化控件
*/
private void initView() {
rb_tj = (RadioButton) findViewById(R.id.rb_tj);
rb_sj = (RadioButton) findViewById(R.id.rb_sj);
rb_fl = (RadioButton) findViewById(R.id.rb_fl);
rb_gd = (RadioButton) findViewById(R.id.rb_gd);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rb_tj:
showFragment(fragment_tj);
break;
case R.id.rb_sj:
showFragment(fragment_sj);
break;
case R.id.rb_fl:
showFragment(fragment_fl);
break;
case R.id.rb_gd:
showFragment(fragment_gd);
break;
}
}
}
可以看到,我们定义了一个全局Fragment,currentFragment,用来标示当前是哪一个Fragment。其中initFragment()方法只是为了初始化所有的Fragment,相信大家也看得出来,最主要的方法是showFragment(),下面我就来说一下这个方法:
/**
71 * 展示Fragment
72 */
73 private void showFragment(Fragment fragment) {
74 if (currentFragment!=fragment) {
75 FragmentTransaction transaction = manager.beginTransaction();
76 transaction.hide(currentFragment);
77 currentFragment = fragment;
78 if (!fragment.isAdded()) {
79 transaction.add(R.id.layout_main_fragment, fragment).show(fragment).commit();
80 } else {
81 transaction.show(fragment).commit();
82 }
83 }
84 }
这个方法主要完成Fragment的隐藏和展示,也就是完成Fragment的切换功能。可以看到,在方法的开始我们先判断一下传入的Fragment是不是当前currentFragment,如果不是的话,我们就隐藏currentFragment,并且将我们传入的Fragment赋值给currentFragment。然后再调用Fragment#isAdded()方法,判断传入的Fragment是否已经被add()过了,如果已经被add()过了,那么就直接FragmentTransaction#show()并且commit()即可,否则的话先add()当前fragment,然后在show()展示出来。这样我们就成功实现了保存加载过的Fragment中的内容了(其实不算保存,只是不让加载过的内容销毁),是不是很简单呢?快下一个小Demo尝试一下吧~
Android中Fragment的Hide和Show的更多相关文章
- Android中Fragment和ViewPager那点事儿(仿微信APP)
在之前的博文<Android中使用ViewPager实现屏幕页面切换和引导页效果实现>和<Android中Fragment的两种创建方式>以及<Android中Fragm ...
- Android中Fragment与Activity之间的交互(两种实现方式)
(未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<Android中Fragment的两种创建方式>,就如 ...
- Android 中Fragment使用
Android 中Fragment使用 public class MainActivity extends Activity { public static String[] array = { &q ...
- Android中Fragment的两种创建方式
fragment是Activity中用户界面的一个行为或者是一部分.你可以在一个单独的Activity上把多个Fragment组合成为一个多区域的UI,并且可以在多个Activity中再使用.你可以认 ...
- Android中fragment之间和Activity的传值、切换
功能介绍:通过一个activity下方的三个按钮,分别是发送消息(sendButton).聊天记录(chatButton).常用语(commonButton).当单击按钮是,来切换上方的fragmen ...
- android中Fragment的使用
android中的Fragment跟网页中的iframe很像,用于在界面上嵌入局部动态内容,我的描述可能不准确,只是我的理解吧 创建Fragment很简单,在Android Studio中是这么创建的 ...
- Android中Fragment生命周期和基本用法
1.基本概念 1. Fragment是什么? Fragment是可以让你的app纵享丝滑的设计,如果你的app想在现在基础上性能大幅度提高,并且占用内存降低,同样的界面Activity占用内存比Fra ...
- Android中Fragment+ViewPager的配合使用
官方推荐 ViewPager与Fragment一起使用,可以更加方便的管理每个Page的生命周期,这里有标准的适配器实现用于ViewPager和Fragment,涵盖最常见的用例.FragmentPa ...
- Android中Fragment的简单介绍
Android是在Android 3.0 (API level 11)引入了Fragment的,中文翻译是片段或者成为碎片(个人理解),可以把Fragment当成Activity中的模块,这个模块有自 ...
随机推荐
- IOS 预览pdf,word文档的集中方式
在iPhone中可以很方便的预览文档文件,如:pdf.word等等,这篇文章将以PDF为例.介绍三种预览PDF的方式,又分别从本地pdf文档和网络上的pdf文档进行对比. 预览本地PDF文档: 1.使 ...
- 《JAVA多线程编程核心技术》 笔记:第四章、Lock的使用
一.使用ReentrantLock类1.1 ReentrantLock的使用:1.2 ReentrantLock的不足:1.3 正确使用Condition实现等待/通知1.4 使用多个Conditio ...
- join-case
SELECT trd.* ,(CASE WHEN ta.AccountID IS null THEN '' ELSE ta.AccountID END ) FROM traceroleid trd L ...
- Numba makes Python code fast
Numba: A High Performance Python Compiler http://numba.pydata.org/ 一行代码让python的运行速度提高100倍,你信吗?-聚能聊-云 ...
- Set 接口常用子类及其特点
Set 集合中元素不可重复,是无序的(存入和取出的顺序是不一样的), Set 接口中的方法和 Collection 接口一致. 常用子类: HashSet : 内部数据结构是哈希表, 是不同步的 Li ...
- django-admin详细设置
Django自带的后台管理是Django明显特色之一,可以让我们快速便捷管理数据.后台管理可以在各个app的admin.py文件中进行控制.以下是我最近摸索总结出比较实用的配置.若你有什么比较好的配置 ...
- 上手Keras
Keras的核心数据是“模型”,模型是一种组织网络层的方式.Keras中主要的模型是Sequential模型,Sequential是一系列网络层按顺序构成的栈. Sequential模型如下: fro ...
- mysql 建立表之间关系 练习 2
创建数据库db6 create database db6 charset=utf8; user db6; # 创建班级表 mysql) not null unique); Query OK, rows ...
- C# 创建单例你会几种方式?
关于为什么需要创建单例?这里不过多介绍,具体百度知. 关于C# 创建单例步骤或条件吧 1.声明静态变量:2.私有构造函数(无法实例化)3.静态创建实例的方法:至于我这里的Singleton是seal ...
- 吴超老师课程---Hadoop的伪分布安装
1.1 设置ip地址 执行命令 service network restart 验证: ifconfig1.2 关闭防火墙 执行命令 service ip ...