原文地址:http://blog.csdn.net/a123demi/article/details/32693037

Fragment要点

Fragment是activity的界面中的一部分或一种行为。

你能够把多个Fragment们组合到一个activity中来创建一个多面界面而且你能够在多个activity中重用一个Fragment。你能够把Fragment觉得模块化的一段activity。它具有自己的生命周期,接收它自己的事件。并能够在activity执行时被加入或删除。

Fragment不能独立存在,它必须嵌入到activity中,并且Fragment的生命周期直接受所在的activity的影响。比如:当activity暂停时,它拥有的全部的Fragment们都暂停了,当activity销毁时,它拥有的全部Fragment们都被销毁。

然而,当activity运行时(在onResume()之后。onPause()之前),你能够单独地操作每一个Fragment,比方加入或删除或替代(add(),remove(),replace())它们。当你在运行上述针对Fragment的事务时。你能够将事务加入到一个棧中。这个栈被activity管理,栈中的每一条都是一个Fragment的一次事务。

有了这个栈,就能够反向运行Fragment的事务,这样就能够在Fragment级支持“返回”键(向后导航)。

而本文简介主要通过点击不同button实现切换相应的fragment的效果。类似用Tab的切换:

主要代码例如以下:

1.project源码显示:

2.编译后效果图

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTEyM2RlbWk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" style="border:none; max-width:100%">

3.切换button布局:activity_bottom_bts.xml切换的button显示在底部

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?

    xmlversionxmlversion="1.0" encoding="utf-8"?>

  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="horizontal">
  6. <Button
  7. android:id="@+id/movie_btn"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:layout_weight="1"
  11. android:gravity="center"
  12. android:text="@string/movie"/>
  13. <Button
  14. android:id="@+id/tv_btn"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_weight="1"
  18. android:gravity="center"
  19. android:text="@string/tv"/>
  20. <Button
  21. android:id="@+id/anime_btn"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:layout_weight="1"
  25. android:gravity="center"
  26. android:text="@string/anime"/>
  27. <Button
  28. android:id="@+id/variety_btn"
  29. android:layout_width="wrap_content"
  30. android:layout_height="wrap_content"
  31. android:layout_weight="1"
  32. android:gravity="center"
  33. android:text="@string/variety" />
  34. </LinearLayout></span></span>

4.主界面activity_main.xml

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><RelativeLayoutxmlns:androidRelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context="com.example.switchfragmentdemo.MainActivity$PlaceholderFragment">
  10. <LinearLayout
  11. android:id="@+id/button_view_include"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:layout_alignParentBottom="true"
  15. >
  16. <includelayoutincludelayout="@layout/activity_bottom_btns" />
  17. </LinearLayout>
  18. <FrameLayout
  19. android:id="@+id/fragment_content"
  20. android:layout_width="match_parent"
  21. android:layout_height="fill_parent"
  22. android:layout_alignParentTop="true"
  23. android:layout_marginBottom="50dp"
  24. android:layout_below="@id/button_view_include"
  25. >
  26. </FrameLayout>
  27. </RelativeLayout></span></span>

5.strings.xml

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
  2. <resources>
  3. <stringnamestringname="app_name">SwitchFragmentDemo</string>
  4. <stringnamestringname="hello_world">Hello world!</string>
  5. <stringnamestringname="action_settings">Settings</string>
  6. <string name="movie">电影</string>
  7. <string name="tv">电视剧</string>
  8. <string name="anime">动漫</string>
  9. <string name="variety">综艺</string>
  10. <stringnamestringname="movie_view">这是一个电影界面</string>
  11. <string name="tv_view">这是一个电视剧界面</string>
  12. <stringnamestringname="anime_view">这是一个动漫界面</string>
  13. <stringnamestringname="variety_view">这是一个综艺界面</string>
  14. </resources></span></span>

6.主界面实现代码:MainActivity.java

  1. <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
  2. importjava.util.ArrayList;
  3. importjava.util.List;
  4. importandroid.annotation.SuppressLint;
  5. importandroid.app.Activity;
  6. importandroid.app.FragmentManager;
  7. importandroid.app.FragmentTransaction;
  8. importandroid.graphics.Color;
  9. importandroid.os.Bundle;
  10. importandroid.view.Menu;
  11. importandroid.view.MenuItem;
  12. importandroid.view.View;
  13. importandroid.view.View.OnClickListener;
  14. importandroid.widget.Button;
  15. @SuppressLint("NewApi")
  16. public classMainActivity extends Activity implements OnClickListener {
  17. private Button movieBtn, tvBtn,animeBtn, varietyBtn;
  18. private List<Button> btnList = newArrayList<Button>();
  19. private FragmentManager fm;
  20. private FragmentTransaction ft;
  21. @Override
  22. protected void onCreate(BundlesavedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. findById();
  26. // 進入系統默認為movie
  27. fm = getFragmentManager();
  28. ft = fm.beginTransaction();
  29. setBackgroundColorById(R.id.movie_btn);
  30. ft.replace(R.id.fragment_content,new MovieFragment());
  31. ft.commit();
  32. }
  33. private void findById() {
  34. movieBtn = (Button)this.findViewById(R.id.movie_btn);
  35. tvBtn = (Button)this.findViewById(R.id.tv_btn);
  36. animeBtn = (Button) this.findViewById(R.id.anime_btn);
  37. varietyBtn = (Button)this.findViewById(R.id.variety_btn);
  38. movieBtn.setOnClickListener(this);
  39. tvBtn.setOnClickListener(this);
  40. animeBtn.setOnClickListener(this);
  41. varietyBtn.setOnClickListener(this);
  42. btnList.add(movieBtn);
  43. btnList.add(tvBtn);
  44. btnList.add(animeBtn);
  45. btnList.add(varietyBtn);
  46. }
  47. private void setBackgroundColorById(intbtnId) {
  48. for (Button btn : btnList) {
  49. if (btn.getId() == btnId){
  50. btn.setBackgroundColor(Color.GREEN);
  51. }else {
  52. btn.setBackgroundColor(Color.BLUE);
  53. }
  54. }
  55. }
  56. @Override
  57. public boolean onCreateOptionsMenu(Menumenu) {
  58. // Inflate the menu; this addsitems to the action bar if it is present.
  59. getMenuInflater().inflate(R.menu.main,menu);
  60. return true;
  61. }
  62. @Override
  63. public booleanonOptionsItemSelected(MenuItem item) {
  64. // Handle action bar item clickshere. The action bar will
  65. // automatically handle clicks onthe Home/Up button, so long
  66. // as you specify a parentactivity in AndroidManifest.xml.
  67. int id = item.getItemId();
  68. if (id == R.id.action_settings) {
  69. return true;
  70. }
  71. returnsuper.onOptionsItemSelected(item);
  72. }
  73. @Override
  74. public void onClick(View v) {
  75. // TODO Auto-generated methodstub
  76. fm = getFragmentManager();
  77. ft = fm.beginTransaction();
  78. switch (v.getId()) {
  79. case R.id.movie_btn:
  80. setBackgroundColorById(R.id.movie_btn);
  81. ft.replace(R.id.fragment_content,new MovieFragment());
  82. break;
  83. case R.id.tv_btn:
  84. setBackgroundColorById(R.id.tv_btn);
  85. ft.replace(R.id.fragment_content,new TVFragment());
  86. break;
  87. case R.id.anime_btn:
  88. setBackgroundColorById(R.id.anime_btn);
  89. ft.replace(R.id.fragment_content,new AnimeFragment());
  90. break;
  91. case R.id.variety_btn:
  92. setBackgroundColorById(R.id.variety_btn);
  93. ft.replace(R.id.fragment_content,new VarietyFragment());
  94. break;
  95. default:
  96. break;
  97. }
  98. // 不要忘记提交
  99. ft.commit();
  100. }
  101. }</span></span>

7.电影界面:fragment_movie.xml和MovieFragment.java

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?xml version="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#FF00FF"
  6. android:orientation="vertical" >
  7. <TextView
  8. android:id="@+id/movie_tv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/movie_view" />
  12. </LinearLayout></span></span>
  1. <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
  2. import android.app.Fragment;
  3. importandroid.os.Bundle;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. public classMovieFragment extends Fragment {
  8. <spanstyle="white-space:pre"> </span>@Override
  9. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  10. Bundle savedInstanceState) {
  11. return inflater.inflate(R.layout.fragment_movie, null);
  12. }
  13. }</span></span>

8.电视剧界面:fragment_tv.xml和TVFragment.java

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#00FFFF"
  6. android:orientation="vertical">
  7. <TextView
  8. android:id="@+id/tv_tv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/tv_view"
  12. />
  13. </LinearLayout></span></span>
  1. <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
  2. importandroid.os.Bundle;
  3. importandroid.app.Fragment;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. public classTVFragment extends Fragment {
  8. <spanstyle="white-space:pre"> </span>@Override
  9. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  10. Bundle savedInstanceState) {
  11. return inflater.inflate(R.layout.fragment_tv, null);
  12. }
  13. }</span></span>

9.动漫界面:fragment_anime和AnimeFragment.java

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?

    >

  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#00FF00"
  6. android:orientation="vertical">
  7. <TextView
  8. android:id="@+id/anime_tv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/anime_view"
  12. />
  13. </LinearLayout></span></span>
  1. <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
  2. importandroid.os.Bundle;
  3. importandroid.annotation.SuppressLint;
  4. importandroid.app.Fragment;
  5. importandroid.view.LayoutInflater;
  6. importandroid.view.View;
  7. importandroid.view.ViewGroup;
  8. @SuppressLint("NewApi")
  9. public classAnimeFragment extends Fragment {
  10. <spanstyle="white-space:pre"> </span>@Override
  11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  12. Bundle savedInstanceState) {
  13. return inflater.inflate(R.layout.fragment_anime, null);
  14. }
  15. }</span></span>

10.综艺界面:fragment_variety和VarietyFragment

  1. <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
  2. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#FFFF00"
  6. android:orientation="vertical">
  7. <TextView
  8. android:id="@+id/variety_tv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/variety_view"/>
  12. </LinearLayout></span></span>
  1. <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
  2. importandroid.os.Bundle;
  3. importandroid.app.Fragment;
  4. importandroid.view.LayoutInflater;
  5. importandroid.view.View;
  6. importandroid.view.ViewGroup;
  7. public classVarietyFragment extends Fragment {
  8. <spanstyle="white-space:pre"> </span>@Override
  9. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  10. Bundle savedInstanceState) {
  11. return inflater.inflate(R.layout.fragment_variety, null);
  12. }
  13. }
  14. </span></span>

上面为代码的详细实现。

源码下载地址:http://download.csdn.net/detail/a123demi/7524047

Android Fragment实现button间的切换的更多相关文章

  1. Android 两个界面间快速切换时,会发现有短暂黑屏

    这种问题一般是因为一个Activity启动之后在显示视图之间时间太长导致的. 1.优化方式可以通过精简layout文件.多线程处理数据载入等. 2.但是有些Activity的layout文件可能比较大 ...

  2. [原]Android Fragment 入门介绍

    Fragment Fragment 产生,优点,用途,使用方法简介 1 Fragmeng简介 自从Android 3.0中引入fragments 的概念,根据词海的翻译可以译为:碎片.片段.其上的是为 ...

  3. Android - fragment Manager

    fragment基本使用: http://www.cnblogs.com/qlky/p/5415679.html Fragmeng优点 Fragment可以使你能够将activity分离成多个可重用的 ...

  4. Android FragmentTransactionExtended:使Fragment以多种样式动画切换

    有多种fragment之间切换的效果,效果是这样的: Demo的实现是很简单的. 在res/values中,新建一个arrays.xml文件,存放Fragment动画效果的名称,在spinner中使用 ...

  5. android中viewPager+fragment实现的屏幕左右切换(进阶篇)

    Fragment支持在不同的Activity中使用并且可以处理自己的输入事件以及生命周期方法等.可以看做是一个子Activity. 先看一下布局: 1 <LinearLayout xmlns:a ...

  6. Android之怎样实现滑动页面切换【Fragment】

    Fragment 页面切换不能滑动 所以对于listview 能够加入的左右滑动事件 .不会有冲突比如(QQ的好友列表的删除)  Fragment 和viewpager 的差别  Viewpager ...

  7. 【转】Android Fragment中使用SurfaceView切换时闪一下黑屏的解决办法

    重构了下之前自己的一个新闻客户端,全部使用了Fragment来进行页面切换,只有一个入口Activity作为程序的启动Activity,其中有一个界面需要调用摄像头识别二维码, 于是就会用到Surfa ...

  8. 【Android自学日记】【转】Android Fragment 真正的完全解析(下)

    上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Frag ...

  9. Android Fragment 真正的完全解析(下)

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和 ...

随机推荐

  1. scala的Map

    package com.test.scala.test object MapTest { def main(args: Array[String]): Unit = { //定义一个不可变的map v ...

  2. [ Luogu Contest 10364 ] TG

    \(\\\) \(\#A\) 小凯的数字 给出两个整数\(L,R\),从\(L\)到\(R\)按顺序写下来,求生成整数对\(9\)取模后的答案. 例如\(L=8,R=12\),生成的数字是\(8910 ...

  3. P1538 迎春舞会之数字舞蹈

    题目背景 HNSDFZ的同学们为了庆祝春节,准备排练一场舞会. 题目描述 在越来越讲究合作的时代,人们注意的更多的不是个人物的舞姿,而是集体的排列. 为了配合每年的倒计时,同学们决定排出——“数字舞蹈 ...

  4. xampp中localhost与DreamWaver站点设置问题

    作为一个初学者,在DreamWaver中配置web服务器用于本地测试,中间碰到了好多问题,百度答案模糊不清,自己摸索出来,把自己碰到的,易错的地方做个总结. step1 : 安装xampp(安装位置记 ...

  5. Android文件操作报open failed: EBUSY (Device or resource busy)

    Android删除文件后重新创建时偶尔出现 open failed: EBUSY (Device or resource busy)错误,该错误是Android系统的一个bug,大概的意思类似于win ...

  6. Hive扩展功能(七)--Hive On Spark

    软件环境: linux系统: CentOS6.7 Hadoop版本: 2.6.5 zookeeper版本: 3.4.8 主机配置: 一共m1, m2, m3这五部机, 每部主机的用户名都为centos ...

  7. antiSMASH数据库:微生物次生代谢物合成基因组簇查询和预测

    2017年4月28日,核酸研究(Nucleic Acids Research)杂志上,在线公布了一个可搜索微生物次生代谢物合成基因组簇的综合性数据库antiSMASH数据库 4.0版,前3版年均引用2 ...

  8. Oracle 函数总结

    <1>=========================返回 String,其中包含有与指定的字符代码相关的字符======================== 函      数:< ...

  9. Vue项目优化首屏加载速度

    Vue项目部署上线后经常会发现首屏加载的速度特别慢:那么有那写能做的简单优化呢 一.路由的懒加载 路由懒加载也就是 把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件. 结合 ...

  10. cstring 转 string

    都通过基本类型来转换即可:CString可以转换为基本类型LPCTSTR,LPCTSTR根据项目编码可以是const char*或者const wchar_t*:string可以用c_str()转换为 ...