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中的模块,这个模块有自 ...
随机推荐
- 下载安装配置与使用MySQL-5.7.12-winx64.zip
第一步:下载安装包 下载 地址:http://www.mysql.com/ 第二步:解压下载包 下载好后解压文件,把内容解压到想要的位置,本例解压到“D:\Program Files\mysql-5. ...
- JavaScript -获取屏窗与视窗、文档宽高
实例:1920*1080的电脑屏幕 1.获取窗口中的文档显示区域宽高 clientw = window.innerWidth; //1920(包含滚动条) clienth = window.inner ...
- What is Grammar?
What is Grammar? And why grammar is your friend… Grammar(noun): the structure and system of a langua ...
- django--个人主页建立练习
1.前端页面采用模板继承与动态模板 {% extends 'base.html' %} {% block content %} {% for article in article_list %} &l ...
- NYOJ 119 士兵杀敌(三)(RMQ算法)
採用的的是小牛的写法,蒟蒻第一次写.. RMQ (Range Minimum/Maximum Query)问题是指:对于长度为n的数列A,回答若干询问RMQ(A,i,j)(i,j<=n).返回数 ...
- struct 模块 把一个类型,如数字,转成固定长度的bytes
该模块可以把一个类型,如数字,转成固定长度的bytes import struct headers=struct.pack('i',132333) print(headers,len(headers) ...
- CDN 环境下获取用户IP方法
CDN 环境下获取用户IP方法 1 cdn 自定义header头的X-Real-IP,在后端使用$http_x_real_ip获得 proxy_set_header X-Real-IP $remote ...
- rails timeout 异常
发现经常有”超时“的错误信息,如/usr/lib/ruby/1.8/timeout.rb:54:in `rbuf_fill': execution expired (Timeout::Error),恩 ...
- s5_day13作业
#对之前文件进行的增删改查操作实现日志操作,日志输出用户进行过的操作. def log(): import logging logger_obj=logging.getLogger() logger_ ...
- 笔记-CSS空背景图片会导致页面被加载两次
如果页面样式的背景图片路径设置为'' 或 '#', 会导致页面被重复加载两次 (Chrome.56.0.2924.87 测试) 因为:空图片路径属性值,默认加载当前页面的URL作为图片路径 Safar ...