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.工程源代码显示:

 Android  Fragment实现按钮间的切换

2.编译后效果图

Android  Fragment实现按钮间的切换Android  Fragment实现按钮间的切换

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.xmlMovieFragment.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_animeAnimeFragment.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_varietyVarietyFragment

<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实现按钮间的切换,布布扣,bubuko.com

Android Fragment实现按钮间的切换

上一篇:Android Wifi子系统源代码View


下一篇:蜗牛—Android基础之简易猜拳游戏