Android安卓Fragment简单实现

Android安卓Fragment简单实现

做项目的时候要做底部按钮的实现,用到的是Fragment,尝试了挺久,想到了两种实现。一个是比较笨是写法,一个是比较好的写法。

效果图如下:

这里写图片描述

先上种写法都一样的代码

因为设置了3个按钮,所以有3个和3个XML,写法差不多,就贴一个就好了。
显示xml中的代码,文件名是:home.xml

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/home"/>

</LinearLayout>

然后是对应的基础了Fragment的代码,文件名是:Home.java

package myandroidapplication.teamofmengmen;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Home extends Fragment {
    private String TAG = "Home";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "Home" + "onCreate");
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "Home" + "onCreateView");
        return inflater.inflate(R.layout.home, container, false);
    }

}

项目中有3个按钮,分别是Dynamic、Home、Me。由于基础代码差不多,所以就列了一个。

接下来就是先写一个比较笨的方法

其实都很简单,直接上代码
先上XML中的代码,文件名是:activity_main_old.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" >

    <!-- 标题栏 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/title_old" />
    </LinearLayout>
    <!-- 正文 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="12"
        android:orientation="vertical" >

        <fragment
            android:id="@+id/fragment_main_dynamic"
            android:name="myandroidapplication.teamofmengmen.Dynamic"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/dynamic" />

        <fragment
            android:id="@+id/fragment_main_home"
            android:name="myandroidapplication.teamofmengmen.Home"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/home" />

        <fragment
            android:id="@+id/fragment_main_me"
            android:name="myandroidapplication.teamofmengmen.Me"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/me" />
    </LinearLayout>

    <!-- 底部按钮 -->

    <LinearLayout
        android:id="@+id/ll_main_bottombutton"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >

        <View
            android:layout_width="match_parent"
            android:layout_height="0.3dp"
            android:background="@android:color/background_dark" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/iv_main_bottombuttom_dynamic"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:contentDescription="@string/imageview"
                android:src="@drawable/main_dynamic" />

            <ImageView
                android:id="@+id/iv_main_bottombuttom_home"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:contentDescription="@string/imageview"
                android:src="@drawable/main_main" />

            <ImageView
                android:id="@+id/iv_main_bottombuttom_me"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:contentDescription="@string/imageview"
                android:src="@drawable/main_me" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

然后是对应继承了FragmentActivity类的代码,文件名为:MainActivity_Old.java

package myandroidapplication.teamofmengmen;

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.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity_Old extends FragmentActivity {
    private ImageView iv_main_bottombuttom_dynamic, iv_main_bottombuttom_home,
            iv_main_bottombuttom_me;

    private Fragment f_home, f_me, f_dynamic;
    private FragmentTransaction ft_me, ft_home, ft_dynamic;
    private FragmentManager fm = getSupportFragmentManager();

    private String TAG = "MainActivity_Old";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main_old);

        Toast.makeText(getApplicationContext(), TAG, Toast.LENGTH_SHORT).show();
        Log.i(TAG, "MainActivity_Old:onCreate");
        setViewById();
        beginFragmentActivity();
        onclick();

    }

    // 通过Id找到对应的View
    private void setViewById() {
        iv_main_bottombuttom_dynamic = (ImageView) findViewById(R.id.iv_main_bottombuttom_dynamic);
        iv_main_bottombuttom_home = (ImageView) findViewById(R.id.iv_main_bottombuttom_home);
        iv_main_bottombuttom_me = (ImageView) findViewById(R.id.iv_main_bottombuttom_me);

        f_me = fm.findFragmentById(R.id.fragment_main_me);
        f_home = fm.findFragmentById(R.id.fragment_main_home);
        f_dynamic = fm.findFragmentById(R.id.fragment_main_dynamic);
    }

    // 进入界面打开的第一个界面
    @SuppressWarnings("deprecation")
    private void beginFragmentActivity() {
        initFragment();
        iv_main_bottombuttom_home.setImageDrawable(getResources().getDrawable(
                R.drawable.main_main_s));
        ft_dynamic.hide(f_dynamic).commit();
        ft_home.show(f_home).commit();
        ft_me.hide(f_me).commit();

    }

    // 点击时加载的各种Fragment
    private void onclick() {
        iv_main_bottombuttom_dynamic.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                initFragment();
                iv_main_bottombuttom_dynamic.setImageDrawable(getResources()
                        .getDrawable(R.drawable.main_dynamic_s));
                ft_dynamic.show(f_dynamic).commit();
                ft_home.hide(f_home).commit();
                ft_me.hide(f_me).commit();
            }
        });
        iv_main_bottombuttom_home.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                initFragment();
                iv_main_bottombuttom_home.setImageDrawable(getResources()
                        .getDrawable(R.drawable.main_main_s));
                ft_dynamic.hide(f_dynamic).commit();
                ft_home.show(f_home).commit();
                ft_me.hide(f_me).commit();
            }
        });
        iv_main_bottombuttom_me.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                initFragment();
                iv_main_bottombuttom_me.setImageDrawable(getResources()
                        .getDrawable(R.drawable.main_me_s));
                ft_dynamic.hide(f_dynamic).commit();
                ft_home.hide(f_home).commit();
                ft_me.show(f_me).commit();
            }
        });

    }

    // 初始化Fragment,每次点击时要进行调用
    @SuppressWarnings("deprecation")
    private void initFragment() {
        ft_me = fm.beginTransaction().hide(f_me);
        ft_home = fm.beginTransaction().hide(f_home);
        ft_dynamic = fm.beginTransaction().hide(f_dynamic);

        iv_main_bottombuttom_dynamic.setImageDrawable(getResources()
                .getDrawable(R.drawable.main_dynamic));
        iv_main_bottombuttom_home.setImageDrawable(getResources().getDrawable(
                R.drawable.main_main));
        iv_main_bottombuttom_me.setImageDrawable(getResources().getDrawable(
                R.drawable.main_me));
    }
}

代码都有注释了,而且很简单,也很好理解把。

接下来就是先写一个相对比较好的方法

为什么说是比较好的呢,因为上面的方法是一Activity就加载了全部Fragment,然而这个新的写法,对内存做了一点点优化,当你没有点击打开新的Fragment时,Fragment不会先加载。
贴上XML中的代码,文件名是: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:orientation="vertical"
    tools:context="myandroidapplication.teamofmengmen.MainActivity" >

    <!-- 底部按钮 -->

    <LinearLayout
        android:id="@+id/ll_main_bottombutton"
        android:layout_width="match_parent"
        android:layout_height="54dp"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >

        <View
            android:layout_width="match_parent"
            android:layout_height="0.3dp"
            android:background="@android:color/background_dark" />

        <RadioGroup
            android:id="@+id/rg_main_bottombutton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rb_main_bottombuttom_dynamic"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:button="@null" />

            <RadioButton
                android:id="@+id/rb_main_bottombuttom_home"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:button="@null" />

            <RadioButton
                android:id="@+id/rb_main_bottombuttom_me"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:button="@null" />
        </RadioGroup>
    </LinearLayout>

    <!-- 正文和标题,由于是代码的问题,所以被写在XML下面 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/ll_main_bottombutton"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@+id/framelayout_main_titleandtext"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

</RelativeLayout>

然后是对应的类,类名为:MainActivity.java

package myandroidapplication.teamofmengmen;

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.util.Log;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends FragmentActivity {

    private RadioButton rb_main_bottombuttom_dynamic,
            rb_main_bottombuttom_home, rb_main_bottombuttom_me;

    private Fragment f_home, f_me, f_dynamic;
    private FragmentManager fm = getSupportFragmentManager();

    private RadioGroup rg_main_bottombutton;

    private String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        setViewById();
        // 对RadioGroup设置监听,点击切换到对应的Fragment
        rg_main_bottombutton
                .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        Log.i(TAG, "rg_main_bottombutton" + checkedId);
                        setBottombuttonSelected(checkedId);
                    }
                });
        // 开始打开的第一个页面
        setBottombuttonSelected(R.id.rb_main_bottombuttom_home);
    }

    // 通过Id设置对应的View
    private void setViewById() {
        rb_main_bottombuttom_dynamic = (RadioButton) findViewById(R.id.rb_main_bottombuttom_dynamic);
        rb_main_bottombuttom_home = (RadioButton) findViewById(R.id.rb_main_bottombuttom_home);
        rb_main_bottombuttom_me = (RadioButton) findViewById(R.id.rb_main_bottombuttom_me);
        rg_main_bottombutton = (RadioGroup) findViewById(R.id.rg_main_bottombutton);
    }

    @SuppressWarnings("deprecation")
    private void setBottombuttonSelected(int checkedId) {
        // 创建一个事务
        FragmentTransaction transaction = fm.beginTransaction();
        // 调用函数进行隐藏
        hideFragments(transaction);
        // 替换按钮的图片
        initFragment();
        // 通过点击得到的Id做对应的动作
        switch (checkedId) {
        case R.id.rb_main_bottombuttom_dynamic:
            Log.i(TAG, "Click:rb_main_bottombuttom_dynamic");
            if (f_dynamic == null) {
                f_dynamic = new Dynamic();
                transaction.add(R.id.framelayout_main_titleandtext, f_dynamic);

            } else {
                transaction.show(f_dynamic);
            }
            rb_main_bottombuttom_dynamic
                    .setCompoundDrawablesWithIntrinsicBounds(
                            null,
                            getResources().getDrawable(
                                    R.drawable.main_dynamic_s), null, null);
            break;
        case R.id.rb_main_bottombuttom_home:
            Log.i(TAG, "Click:rb_main_bottombuttom_home");
            if (f_home == null) {
                f_home = new Home();
                transaction.add(R.id.framelayout_main_titleandtext, f_home);

            } else {
                transaction.show(f_home);
            }
            rb_main_bottombuttom_home.setCompoundDrawablesWithIntrinsicBounds(
                    null, getResources().getDrawable(R.drawable.main_main_s),
                    null, null);
            break;
        case R.id.rb_main_bottombuttom_me:
            Log.i(TAG, "Click:rb_main_bottombuttom_me");
            if (f_me == null) {
                f_me = new Me();
                transaction.add(R.id.framelayout_main_titleandtext, f_me);

            } else {
                transaction.show(f_me);
            }
            rb_main_bottombuttom_me.setCompoundDrawablesWithIntrinsicBounds(
                    null, getResources().getDrawable(R.drawable.main_me_s),
                    null, null);
            break;
        }
        // 最后要提交事物,每个事务只能提交一次
        transaction.commit();
    }

    // 隐藏所有的Fragment
    private void hideFragments(FragmentTransaction transaction) {
        if (f_dynamic != null) {
            transaction.hide(f_dynamic);
        }
        if (f_home != null) {
            transaction.hide(f_home);
        }
        if (f_me != null) {
            transaction.hide(f_me);
        }

    }

    // 初始化按钮的图片显示
    @SuppressWarnings("deprecation")
    private void initFragment() {

        rb_main_bottombuttom_dynamic.setCompoundDrawablesWithIntrinsicBounds(
                null, getResources().getDrawable(R.drawable.main_dynamic),
                null, null);
        rb_main_bottombuttom_home.setCompoundDrawablesWithIntrinsicBounds(null,
                getResources().getDrawable(R.drawable.main_main), null, null);
        rb_main_bottombuttom_me.setCompoundDrawablesWithIntrinsicBounds(null,
                getResources().getDrawable(R.drawable.main_me), null, null);
    }
}

最后发一下源码

点击下载源码

需要注意一下:

要查看两种方式的实现效果需要看下AndroidManifest.xml这个文件中的这段代码:

 <!-- 旧的Fragment实现方法,开始项目时调用 ,去掉注释可以使用 -->
        <!--
        <activity 
            android:name=".MainActivity_Old"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        -->


        <!-- 新的Fragment实现方法,开始项目时调用 -->
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

修改此代码可以看到两种不同写法的实现效果。

这篇博客到此接受,感谢阅读。有哪里写不好的地方希望大家指出。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值