zoukankan      html  css  js  c++  java
  • 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.编译后效果图


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

    [html] view plain copy
     print?
    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.    
    7.     <Button  
    8.         android:id="@+id/movie_btn"  
    9.        android:layout_width="wrap_content"  
    10.        android:layout_height="wrap_content"  
    11.         android:layout_weight="1"  
    12.         android:gravity="center"  
    13.         android:text="@string/movie"/>  
    14.    
    15.     <Button  
    16.         android:id="@+id/tv_btn"  
    17.        android:layout_width="wrap_content"  
    18.        android:layout_height="wrap_content"  
    19.         android:layout_weight="1"  
    20.         android:gravity="center"  
    21.         android:text="@string/tv"/>  
    22.    
    23.     <Button  
    24.         android:id="@+id/anime_btn"  
    25.        android:layout_width="wrap_content"  
    26.        android:layout_height="wrap_content"  
    27.         android:layout_weight="1"  
    28.         android:gravity="center"  
    29.         android:text="@string/anime"/>  
    30.    
    31.     <Button  
    32.         android:id="@+id/variety_btn"  
    33.        android:layout_width="wrap_content"  
    34.        android:layout_height="wrap_content"  
    35.         android:layout_weight="1"  
    36.         android:gravity="center"  
    37.        android:text="@string/variety" />  
    38.    
    39. </LinearLayout></span></span>  


    4.主界面activity_main.xml

    [html] view plain copy
     print?
    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.    
    11.     <LinearLayout  
    12.        android:id="@+id/button_view_include"  
    13.        android:layout_width="fill_parent"  
    14.        android:layout_height="wrap_content"  
    15.        android:layout_alignParentBottom="true"  
    16.         >  
    17.    
    18.         <includelayoutincludelayout="@layout/activity_bottom_btns" />  
    19.     </LinearLayout>  
    20.    
    21.     <FrameLayout  
    22.        android:id="@+id/fragment_content"  
    23.        android:layout_width="match_parent"  
    24.        android:layout_height="fill_parent"  
    25.         android:layout_alignParentTop="true"  
    26.        android:layout_marginBottom="50dp"  
    27.        android:layout_below="@id/button_view_include"  
    28.         >  
    29.     </FrameLayout>  
    30.    
    31. </RelativeLayout></span></span>  



    5.strings.xml

    [html] view plain copy
     print?
    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.      
    7.     <string name="movie">电影</string>  
    8.     <string name="tv">电视剧</string>  
    9.     <string name="anime">动漫</string>  
    10.         <string name="variety">综艺</string>  
    11.          
    12.         <stringnamestringname="movie_view">这是一个电影界面</string>  
    13.         <string name="tv_view">这是一个电视剧界面</string>  
    14.         <stringnamestringname="anime_view">这是一个动漫界面</string>  
    15.         <stringnamestringname="variety_view">这是一个综艺界面</string>  
    16. </resources></span></span>  


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

    [java] view plain copy
     print?

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


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

    [html] view plain copy
     print?

    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>  


    [java] view plain copy
     print?
    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.     
    8. public classMovieFragment extends Fragment {  
    9. <spanstyle="white-space:pre"> </span>@Override   
    10.    public View onCreateView(LayoutInflater inflater, ViewGroup container,    
    11.            Bundle savedInstanceState) {    
    12.        return inflater.inflate(R.layout.fragment_movie, null);    
    13.     }   
    14. }</span></span>  


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

    [html] view plain copy
     print?
    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>  


    [java] view plain copy
     print?
    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.    
    8. public classTVFragment extends Fragment {  
    9. <spanstyle="white-space:pre"> </span>@Override   
    10.    public View onCreateView(LayoutInflater inflater, ViewGroup container,    
    11.            Bundle savedInstanceState) {    
    12.        return inflater.inflate(R.layout.fragment_tv, null);    
    13.     }   
    14. }</span></span>  


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

    [html] view plain copy
     print?

    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>  


    [java] view plain copy
     print?
    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.     
    9. @SuppressLint("NewApi")  
    10. public classAnimeFragment extends Fragment {  
    11. <spanstyle="white-space:pre"> </span>@Override   
    12.    public View onCreateView(LayoutInflater inflater, ViewGroup container,    
    13.            Bundle savedInstanceState) {    
    14.        return inflater.inflate(R.layout.fragment_anime, null);    
    15.     }   
    16. }</span></span>  


    10.综艺界面:fragment_variety和VarietyFragment

    [html] view plain copy
     print?
    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>  


    [java] view plain copy
     print?

    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.    
    8. public classVarietyFragment extends Fragment {  
    9. <spanstyle="white-space:pre"> </span>@Override   
    10.    public View onCreateView(LayoutInflater inflater, ViewGroup container,    
    11.            Bundle savedInstanceState) {    
    12.        return inflater.inflate(R.layout.fragment_variety, null);    
    13.     }   
    14. }  
    15. </span></span>  


    上面为代码的详细实现。

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

  • 相关阅读:
    Linux 第一个脚本程序
    Linux 8开启FTP功能服务
    PPT 倒计时时钟,用 GIF 动画实现,可直接使用 -- 附 Python 实现代码
    python flask 虚拟环境迁移
    GOLANG学习之路之二
    Golang学习之路之一
    vscode 调试flask项目 解决(socket.gaierror: [Errno 11001] getaddrinfo failed)
    windows下部署 flask (win10+flask+nginx)
    git入门
    配置maven的国内镜像
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/7091148.html
Copyright © 2011-2022 走看看