码迷,mamicode.com
首页 > 其他好文 > 详细

Fragment切换的演示

时间:2016-05-12 14:13:56      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

首先创建主布局文件,即activity_main.xml,代码如下
<RelativeLayout xmlns: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.day17_fragment.MainActivity" >

    <RadioGroup
        android:id="@+id/rg_btns"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/btn_menu1"
            style="@style/radiobutton"
            android:tag="1"
            android:drawableTop="@drawable/menu1"
            android:text="礼物" />

        <RadioButton
            android:id="@+id/btn_menu2"
            style="@style/radiobutton"
            android:tag="2"
            android:drawableTop="@drawable/menu2"
            android:text="朋友圈" />

        <RadioButton
            android:id="@+id/btn_menu5"
            style="@style/radiobutton"
            android:tag="5"
            android:drawableTop="@drawable/menu5"
            android:text="游戏"/>


        <RadioButton
            android:id="@+id/btn_menu3"
            style="@style/radiobutton"
            android:tag="3"
            android:drawableTop="@drawable/menu3"
           android:text="个人" />

        <RadioButton
            android:id="@+id/btn_menu4"
            style="@style/radiobutton"
            android:tag="4"
            android:drawableTop="@drawable/menu4"
           android:text="赚钱"/>
    </RadioGroup>
    <FrameLayout 
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/rg_btns"></FrameLayout>
</RelativeLayout>
这里使用了RadioButton进行界面的切换,相同属性值我都写在样式里了,这里只是引用一下,这不是重点.在按钮上方使用了FrameLayout作为Fragment的容器,为什么使用帧布局呢,毕竟方便.

其次,创建五个Fragment布局,差不多的布局,我就写一个了.以下是代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第1个fragment" />

</LinearLayout>
这里的textview只是为了区分不同的Fragment.

布局文件创建好了,我们开始写代码了.

首先创建自己的Fragment类,如:FristFragment,然后继承Fragment.导包不要导错,我是用的v4兼容包.
以下是Fragment类的代码:

package com.example.day17_fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.firstfragment,container,false);
    }
}
这是第一个Fragment的代码,剩下的基本都是一样的步骤.就是onCreateView方法的返回值中,将R.layout.firstfragment替换成你的其他Fragment的布局文件.就不罗嗦了.

在所有的自定义的Fragment类都写好了后,开始写MainActivity了,以下是代码:
package com.example.day17_fragment;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends FragmentActivity {
    private RadioGroup rg_btns;
    private FragmentManager fm = getSupportFragmentManager();
    private Fragment fir, sec, thri, forth, fif;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initList();
        //默认显示的fragment
        selectBtn(R.id.btn_menu5);

        rg_btns.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {         
                selectBtn(checkedId);
            }
        });
    }
    //通过按钮选择对应的Fragment
    private void selectBtn(int checkedId) {
        FragmentTransaction ft = fm.beginTransaction();
        isNull(ft);
        switch (checkedId) {
        case R.id.btn_menu5:
            // 主页
            if (fif == null) {
                fif = new FifthFragment();
                ft.add(R.id.content, fif);
            } else {
                ft.show(fif);
            }
            break;
        case R.id.btn_menu1:
            if (fir == null) {
                fir = new FirstFragment();
                ft.add(R.id.content, fir);
            } else {
                ft.show(fir);
            }
            break;
        case R.id.btn_menu2:
            if (sec == null) {
                sec = new SecondFragment();
                ft.add(R.id.content, sec);
            } else {
                ft.show(sec);
            }
            break;
        case R.id.btn_menu3:
            if (thri == null) {
                thri = new ThridFragment();
                ft.add(R.id.content, thri);
            } else {
                ft.show(thri);
            }
            break;
        case R.id.btn_menu4:
            if (forth == null) {
                forth = new ForthFragemnt();
                ft.add(R.id.content, forth);
            } else {
                ft.show(forth);
            }
            break;

        default:
            break;
        }
        //别忘了,要commit.千万别忘了
        ft.commit();
    }
    private void isNull(FragmentTransaction ft) {
        if (fif != null) {
            ft.hide(fif);
        }
        if (fir != null) {
            ft.hide(fir);
        }
        if (sec != null) {
            ft.hide(sec);
        }
        if (thri != null) {
            ft.hide(thri);
        }
        if (forth != null) {
            ft.hide(forth);
        }
    }


//初始化控件,虽然只有一个,但还是要养成这样的习惯.
    private void initView() {
        rg_btns = (RadioGroup) findViewById(R.id.rg_btns);
    }
}
在MainActivity中,首先是初始化控件.设置RadioGroup的监听事件,然后通过对应的按钮找到对应的Fragment,是不是很简单.就是选择Fragment的代码多了一些.我加了很多判断Fragment的判断是为了优化代码,判断Fragment是否为null,这样才会在点击按钮之后再创建,不然在布局加载的时候都创建了,我又不用不就浪费了么.Last but not least,别导错包,v4包,所以因为导的是v4包,这里的MainActivity就不能继承Activity了,要继承FragmentActivity.这是容易遗漏的地方.

然后代码貌似还是很多很不爽,就想了一个可以减少代码的方式.先给看一下减少后的代码:
package com.example.day17_fragment;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends FragmentActivity {
    private RadioGroup rg_btns;
    private FragmentManager fm = getSupportFragmentManager();
    private Fragment fir, sec, thri, forth, fif;
    private List<Fragment> list = new ArrayList<Fragment>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //默认显示
        fm.beginTransaction().add(R.id.content, list.get(4)).commit();
        rg_btns.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                int num = Integer.parseInt(rb.getTag().toString())-1;
                fm.beginTransaction().replace(R.id.content, list.get(num)).commit();        
            }       
        });
    }
    //将Fragment对象加入集合中
    private void initList() {
        list.add(new FirstFragment());
        list.add(new SecondFragment());
        list.add(new ThridFragment());
        list.add(new ForthFragemnt());
        list.add(new FifthFragment());
    }
    //初始化控件
    private void initView() {
        rg_btns = (RadioGroup) findViewById(R.id.rg_btns);
    }

}

这里使用了一个集合来存储Fragment对象,然后在RadioGroup的监听事件里通过CheckedId来查找RadioButton,获得对应的Tag属性值(还记得我在主布局RadioButton中的Tag属性么,就是为此特意加的),作为集合的索引.这里的方法是笨方法.代码灵活性较差,但毕竟能减少这么多代码,况且Fragment的数量屈指可数,便也就无伤大雅了.
以下图片是最终效果:
技术分享技术分享技术分享技术分享技术分享
好吧,这其实就是我的家庭作业,顺便整理一下,作为我的第一个技术博文吧.

Fragment切换的演示

标签:

原文地址:http://blog.csdn.net/sinat_26930827/article/details/51366516

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!