Android Fragment实现按钮间的切换

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级支持“返回”键(向后导航)。

而本文简单介绍主要通过点击不同按钮实现切换对应的fragment的效果,类似用Tab的切换:

主要代码如下:

1.工程源代码显示:

2.编译后效果图

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

<span style="font-family:SimSun;"><span style="font-size:18px;"><?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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: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"
        >

        <includelayout="@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;"><?xmlversion="1.0" encoding="utf-8"?>
<resources>
    <stringname="app_name">SwitchFragmentDemo</string>
    <stringname="hello_world">Hello world!</string>
    <stringname="action_settings">Settings</string>

    <string name="movie">电影</string>
    <string name="tv">电视剧</string>
    <string name="anime">动漫</string>
        <string name="variety">综艺</string>

        <stringname="movie_view">这是一个电影界面</string>
        <string name="tv_view">这是一个电视剧界面</string>
        <stringname="anime_view">这是一个动漫界面</string>
        <stringname="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: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;"><?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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;"><?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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;"><?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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>

上面为代码的具体实现。

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

Android Fragment实现按钮间的切换

时间: 2024-12-09 05:48:22

Android Fragment实现按钮间的切换的相关文章

Android Fragment实现button间的切换

原文地址:http://blog.csdn.net/a123demi/article/details/32693037 Fragment要点 Fragment是activity的界面中的一部分或一种行为. 你能够把多个Fragment们组合到一个activity中来创建一个多面界面而且你能够在多个activity中重用一个Fragment.你能够把Fragment觉得模块化的一段activity.它具有自己的生命周期,接收它自己的事件.并能够在activity执行时被加入或删除. Fragmen

Android Fragment 切换动画设置

在Activity跳转之间可以设置动画效果,例如平移,渐变,旋转等动画,当然在Fragment中也可以设置切换的动画效果,可以达到跟ViewPager切换动画类似的效果.在Fragment中设置自定义切换动画主要分为了两种情景,一种是使用 android.app.Fragment包里面的Fragment类时,FragmentManager里面的FragmentTransaction事务只支持XML中的animator标签,如objectAnimator属性动画,不支持传统的补间动画标签如<tra

Android Fragment 真正的完全解析

出处: 自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~ 本篇博客力求为大家说明Fragment如何产生,什么是Fragment,Fragment生命周期,如何静态和动态的使用Fragment,Fragment回退栈,Fragment事务:以及Fragment的一些特殊用途,例如:没有布局的Fragment有何用处?Fragment如何与Activity交互?Fragment如何创建对话框?

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

上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Fragment回退栈,Fragment如何与Activity交互,Fragment与Activity交互的最佳实践,没有视图的Fragment的用处,使用Fragment创建对话框,如何与ActionBar,MenuItem集成等~~ 1.管理Fragment回退栈 类似与Android系统为Activi

android fragment 博客 学习记录

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Fragment回退栈,Fragment如何与Activity交互,Fragment与Activity交互的最佳实践,没有视图的Fragment的用处,使用Fragment创

Android Fragment 你应该知道的一切

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/42628537,本文出自:[张鸿洋的博客] 本文目标教你如何用好Fragment,即Fragment的一些使用的建议,(多数内容来自:android programming the big nerd ranch guide 一书,直接百度,你懂的,虽然是基础书籍,还是很值得一看的). 1.概述 首先我们简单回顾一下,相信大家对Fragment的都不陌生,对于Fragment的使用

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

Android Fragment 真正的完全解析(下) 标签: AndroidFragmentDialogFragmentMenuItem 目录(?)[-] 管理Fragment回退栈 Fragment与Activity通信 Fragment与Activity通信的最佳实践 如何处理运行时配置发生变化 Fragmeny与ActionBar和MenuItem集成 没有布局的Fragment的作用 使用Fragment创建对话框 转载请标明出处:http://blog.csdn.net/lmj623

Android Fragment 真正的完全解析(下)---转

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Fragment回退栈,Fragment如何与Activity交互,Fragment与Activity交互的最佳实践,没有视图的Fragment的用处,使用Fragment创

Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复

Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状态之外, 还需要用户手动保存一些成员变量. Fragment的状态有它自己的实例状态和其中的View状态, 因为其生命周期的灵活性和实际需要的不同, 情况会多一些. 根据源码, 列出了Fragment中实例状态和View状态保存和恢复的几个入口, 便于分析查看. 最后专门讲了WebView状态保存和