Android Fragment实现button间的切换
原文地址: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显示在底部
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?
xmlversionxmlversion="1.0" encoding="utf-8"?>
- <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <Button
- android:id="@+id/movie_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:text="@string/movie"/>
- <Button
- android:id="@+id/tv_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:text="@string/tv"/>
- <Button
- android:id="@+id/anime_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:text="@string/anime"/>
- <Button
- android:id="@+id/variety_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:text="@string/variety" />
- </LinearLayout></span></span>
4.主界面activity_main.xml
- <span style="font-family:SimSun;"><span style="font-size:18px;"><RelativeLayoutxmlns:androidRelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="com.example.switchfragmentdemo.MainActivity$PlaceholderFragment">
- <LinearLayout
- android:id="@+id/button_view_include"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- >
- <includelayoutincludelayout="@layout/activity_bottom_btns" />
- </LinearLayout>
- <FrameLayout
- android:id="@+id/fragment_content"
- android:layout_width="match_parent"
- android:layout_height="fill_parent"
- android:layout_alignParentTop="true"
- android:layout_marginBottom="50dp"
- android:layout_below="@id/button_view_include"
- >
- </FrameLayout>
- </RelativeLayout></span></span>
5.strings.xml
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
- <resources>
- <stringnamestringname="app_name">SwitchFragmentDemo</string>
- <stringnamestringname="hello_world">Hello world!</string>
- <stringnamestringname="action_settings">Settings</string>
- <string name="movie">电影</string>
- <string name="tv">电视剧</string>
- <string name="anime">动漫</string>
- <string name="variety">综艺</string>
- <stringnamestringname="movie_view">这是一个电影界面</string>
- <string name="tv_view">这是一个电视剧界面</string>
- <stringnamestringname="anime_view">这是一个动漫界面</string>
- <stringnamestringname="variety_view">这是一个综艺界面</string>
- </resources></span></span>
6.主界面实现代码:MainActivity.java
- <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
- importjava.util.ArrayList;
- importjava.util.List;
- importandroid.annotation.SuppressLint;
- importandroid.app.Activity;
- importandroid.app.FragmentManager;
- importandroid.app.FragmentTransaction;
- importandroid.graphics.Color;
- importandroid.os.Bundle;
- importandroid.view.Menu;
- importandroid.view.MenuItem;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- @SuppressLint("NewApi")
- public classMainActivity extends Activity implements OnClickListener {
- private Button movieBtn, tvBtn,animeBtn, varietyBtn;
- private List<Button> btnList = newArrayList<Button>();
- private FragmentManager fm;
- private FragmentTransaction ft;
- @Override
- protected void onCreate(BundlesavedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- findById();
- // 進入系統默認為movie
- fm = getFragmentManager();
- ft = fm.beginTransaction();
- setBackgroundColorById(R.id.movie_btn);
- ft.replace(R.id.fragment_content,new MovieFragment());
- ft.commit();
- }
- private void findById() {
- movieBtn = (Button)this.findViewById(R.id.movie_btn);
- tvBtn = (Button)this.findViewById(R.id.tv_btn);
- animeBtn = (Button) this.findViewById(R.id.anime_btn);
- varietyBtn = (Button)this.findViewById(R.id.variety_btn);
- movieBtn.setOnClickListener(this);
- tvBtn.setOnClickListener(this);
- animeBtn.setOnClickListener(this);
- varietyBtn.setOnClickListener(this);
- btnList.add(movieBtn);
- btnList.add(tvBtn);
- btnList.add(animeBtn);
- btnList.add(varietyBtn);
- }
- private void setBackgroundColorById(intbtnId) {
- for (Button btn : btnList) {
- if (btn.getId() == btnId){
- btn.setBackgroundColor(Color.GREEN);
- }else {
- btn.setBackgroundColor(Color.BLUE);
- }
- }
- }
- @Override
- public boolean onCreateOptionsMenu(Menumenu) {
- // Inflate the menu; this addsitems to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main,menu);
- return true;
- }
- @Override
- public booleanonOptionsItemSelected(MenuItem item) {
- // Handle action bar item clickshere. The action bar will
- // automatically handle clicks onthe Home/Up button, so long
- // as you specify a parentactivity in AndroidManifest.xml.
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- return true;
- }
- returnsuper.onOptionsItemSelected(item);
- }
- @Override
- public void onClick(View v) {
- // TODO Auto-generated methodstub
- fm = getFragmentManager();
- ft = fm.beginTransaction();
- switch (v.getId()) {
- case R.id.movie_btn:
- setBackgroundColorById(R.id.movie_btn);
- ft.replace(R.id.fragment_content,new MovieFragment());
- break;
- case R.id.tv_btn:
- setBackgroundColorById(R.id.tv_btn);
- ft.replace(R.id.fragment_content,new TVFragment());
- break;
- case R.id.anime_btn:
- setBackgroundColorById(R.id.anime_btn);
- ft.replace(R.id.fragment_content,new AnimeFragment());
- break;
- case R.id.variety_btn:
- setBackgroundColorById(R.id.variety_btn);
- ft.replace(R.id.fragment_content,new VarietyFragment());
- break;
- default:
- break;
- }
- // 不要忘记提交
- ft.commit();
- }
- }</span></span>
7.电影界面:fragment_movie.xml和MovieFragment.java
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?xml version="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#FF00FF"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/movie_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/movie_view" />
- </LinearLayout></span></span>
- <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
- import android.app.Fragment;
- importandroid.os.Bundle;
- importandroid.view.LayoutInflater;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- public classMovieFragment extends Fragment {
- <spanstyle="white-space:pre"> </span>@Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment_movie, null);
- }
- }</span></span>
8.电视剧界面:fragment_tv.xml和TVFragment.java
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
- <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00FFFF"
- android:orientation="vertical">
- <TextView
- android:id="@+id/tv_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/tv_view"
- />
- </LinearLayout></span></span>
- <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
- importandroid.os.Bundle;
- importandroid.app.Fragment;
- importandroid.view.LayoutInflater;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- public classTVFragment extends Fragment {
- <spanstyle="white-space:pre"> </span>@Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment_tv, null);
- }
- }</span></span>
9.动漫界面:fragment_anime和AnimeFragment.java
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?
>
- <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00FF00"
- android:orientation="vertical">
- <TextView
- android:id="@+id/anime_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/anime_view"
- />
- </LinearLayout></span></span>
- <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
- importandroid.os.Bundle;
- importandroid.annotation.SuppressLint;
- importandroid.app.Fragment;
- importandroid.view.LayoutInflater;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- @SuppressLint("NewApi")
- public classAnimeFragment extends Fragment {
- <spanstyle="white-space:pre"> </span>@Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment_anime, null);
- }
- }</span></span>
10.综艺界面:fragment_variety和VarietyFragment
- <span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversionxmlversion="1.0" encoding="utf-8"?>
- <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#FFFF00"
- android:orientation="vertical">
- <TextView
- android:id="@+id/variety_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/variety_view"/>
- </LinearLayout></span></span>
- <span style="font-family:SimSun;"><span style="font-size:18px;">packagecom.example.myandroidswitchbtndemo;
- importandroid.os.Bundle;
- importandroid.app.Fragment;
- importandroid.view.LayoutInflater;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- public classVarietyFragment extends Fragment {
- <spanstyle="white-space:pre"> </span>@Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment_variety, null);
- }
- }
- </span></span>
上面为代码的详细实现。
Android Fragment实现button间的切换的更多相关文章
- Android 两个界面间快速切换时,会发现有短暂黑屏
这种问题一般是因为一个Activity启动之后在显示视图之间时间太长导致的. 1.优化方式可以通过精简layout文件.多线程处理数据载入等. 2.但是有些Activity的layout文件可能比较大 ...
- [原]Android Fragment 入门介绍
Fragment Fragment 产生,优点,用途,使用方法简介 1 Fragmeng简介 自从Android 3.0中引入fragments 的概念,根据词海的翻译可以译为:碎片.片段.其上的是为 ...
- Android - fragment Manager
fragment基本使用: http://www.cnblogs.com/qlky/p/5415679.html Fragmeng优点 Fragment可以使你能够将activity分离成多个可重用的 ...
- Android FragmentTransactionExtended:使Fragment以多种样式动画切换
有多种fragment之间切换的效果,效果是这样的: Demo的实现是很简单的. 在res/values中,新建一个arrays.xml文件,存放Fragment动画效果的名称,在spinner中使用 ...
- android中viewPager+fragment实现的屏幕左右切换(进阶篇)
Fragment支持在不同的Activity中使用并且可以处理自己的输入事件以及生命周期方法等.可以看做是一个子Activity. 先看一下布局: 1 <LinearLayout xmlns:a ...
- Android之怎样实现滑动页面切换【Fragment】
Fragment 页面切换不能滑动 所以对于listview 能够加入的左右滑动事件 .不会有冲突比如(QQ的好友列表的删除) Fragment 和viewpager 的差别 Viewpager ...
- 【转】Android Fragment中使用SurfaceView切换时闪一下黑屏的解决办法
重构了下之前自己的一个新闻客户端,全部使用了Fragment来进行页面切换,只有一个入口Activity作为程序的启动Activity,其中有一个界面需要调用摄像头识别二维码, 于是就会用到Surfa ...
- 【Android自学日记】【转】Android Fragment 真正的完全解析(下)
上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Frag ...
- Android Fragment 真正的完全解析(下)
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和 ...
随机推荐
- ORCLE 服务器下 in、instr、like的速度比较
情景一(百万级数据):有一个表 (JG_COLLECT_FORM_QGZYXFPHFWJGJC1 ) 有数据条数 :1177472 条 结果:330542条 1.in: SELECT count( ...
- Zookeeper概念学习系列之zookeeper的数据模型
1.层次化的目录结构,命名符合常规文件系统规范. 2.每个节点在zookeeper中叫做znode,并且有其有一个唯一的路径标识. 3.znode中的数据可以有多个版本,比如某一路径下存有多个数据版本 ...
- Python随笔-切片
Python为取list部分元素提供了切片操作,list[begin:end]获取list的[begin,end)区间元素. 可以用负数索引. tuple.str都是list的一种,所以也适用. 可以 ...
- Python之IPython开发实践
Python之IPython开发实践 1. IPython有行号. 2. Tab键自动完成,当前命名空间任何与已输入字符串相匹配的变量就会被找出来. 3. 内省机制,在变量前或者后面加上(?)问号,就 ...
- 移动web——轮播图
1.我们将5张图片又前后各增加一张,第一张前增加的是原本的第五张,第五张后增加的是原本的第一张,增加的原因无非是手指滑动的时候有轮播效果,这不像以前的轮播图,点击图标就能立刻将ul跳转到指定位置,手机 ...
- CSS——行高
浏览器默认文字大小:16px 行高:是基线与基线之间的距离 行高=文字高度+上下边距 一行文字行高和父元素高度一致的时候,垂直居中显示. <!DOCTYPE html> <html& ...
- smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp
报错信息 smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp7,DsmowAA3uguL7e1cyvkyFw--.22553S3 1559096715,ple ...
- mysql zip版本如何安装
1.下载mysqlzip包并解压到D:\javadeveloper\mysql-5.6.24-winx642.配置环境变量在path中添加路径 D:\javadeveloper\mysql-5.6.2 ...
- 关于css定位的一些总结
#pay_pic{ overflow: hidden; width: 200px; margin: 0 auto; } table.dataintable { margin-top: 15px; bo ...
- 【剑指Offer】65、矩阵中的路径
题目描述: 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径.路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子.如果一条路径经 ...