SuperExample之主页的搭建实现底部的TabLayout

来源:互联网 发布:网络营销必备软件 编辑:程序博客网 时间:2024/06/05 15:21

准备写一个各种使用较广的组件、框架、特效、功能等的使用例子的集成app,然后用博客记录下开发的过程;


主页面的页面命名为NAvigationActivity,布局文件为activity_navigation.xml;

布局文件如下:

activity_navigation.xml     

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              xmlns:app="http://schemas.android.com/apk/res-auto"              android:id="@+id/linearlayout"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:orientation="vertical">    <RelativeLayout        android:id="@+id/fragmen_content"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1">    </RelativeLayout>    <include layout="@layout/tab_layout"></include></LinearLayout>


tab_layout.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="0.5dp"        android:background="#e5e5e5">    </RelativeLayout>    <android.support.design.widget.TabLayout        android:id="@+id/tabLayout"        android:layout_width="match_parent"        android:layout_height="50dp">    </android.support.design.widget.TabLayout></RelativeLayout>

布局文件写好了,接下来就是在代码中的使用了:

首先向TabLayout中添加tab:

mTabLayout.addTab(mTabLayout.newTab().setText("消息")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector1)));        mTabLayout.addTab(mTabLayout.newTab().setText("联系人")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector2)), true);        mTabLayout.addTab(mTabLayout.newTab().setText("动态")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector3)));

mTabLayout既是从布局文件中获取的TabLayout控件,在这里加入了三个TAb,分别给这三个Tab设置了文字和图片;


接下来就是设置Tab的选择监听:

mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {            @Override            public void onTabSelected(TabLayout.Tab tab) {                // TODO 当tab被选择时调用                // 根据tab.getPosition()获取tab的位置            }            @Override            public void onTabUnselected(TabLayout.Tab tab) {                // TODO 当tab退出所选状态时调用                // 根据tab.getPosition()获取tab的位置            }            @Override            public void onTabReselected(TabLayout.Tab tab) {                // TODO 当tab被重复选择时调用                // 根据tab.getPosition()获取tab的位置            }        });




可以看到文字没有显示出来,指示器的位置出现在下方;文字没显示是因为文字的颜色和背景色一致了,而只是其默认位置就是在下方,而且我也没找到设置其位置的方法,有哪位知道方法的还请指点一下;


此处既然是当做底部tab的话,我这个地方设计时不需要指示器的(如果在项目中一定需要这么一个在上方的指示器的话,可以采用给Tablayout添加自定义tab的方法实现)

那么我们可以在此处设置指示器的高度为0,将其隐藏起来就可以,同时我们也重新设置一下指示器的颜色以及其他的一些属性

// 设置指示器的颜色        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff00ff"));        // 设置指示器的高度,设置为0则不显示指示器        mTabLayout.setSelectedTabIndicatorHeight(0);        /**         * 设置Tab在未选中和选中状态下的字体颜色,参数必须要传入表示颜色的int值,传入资源文件表示的int怎无效;         * 例如:mTableLayout.setTabTextColors(android.R.color.darker_gray, android.R.color.holo_blue_bright)无效;         * mTableLayout.setTabTextColors(getResources().getColor(android.R.color.darker_gray), getResources().getColor(android.R.color.holo_blue_bright))有效;         * mTableLayout.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#ff00ff"));传入的也是表示颜色的int值;         */        mTabLayout.setTabTextColors(getResources().getColor(android.R.color.darker_gray),                getResources().getColor(android.R.color.holo_blue_bright));        // 设置整个tabLayout的背景图片        Drawable drawable = getResources().getDrawable(R.drawable.bg);        drawable.setAlpha(100);        mTabLayout.setBackground(drawable);        // 当tab比较多的时候可以通过以下的代码来设置TabLayout是可以滑动的        //        mTableLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

效果:

 


之前说过可以通过自定义的View来作为tab,以下是实现的代码:

 /**     * 加载自定义布局的TabLayout     */    private void initTabLayoutForCustom() {        LayoutInflater inflater = LayoutInflater.from(this);        int[] drawables = new int[]{R.drawable.tablayout_selector1, R.drawable.tablayout_selector2, R.drawable.tablayout_selector3};        final String[] texts = new String[]{"消息", "联系人", "动态"};        for (int i = 0; i < 3; i++) {            TabLayout.Tab tab = mTabLayout.newTab();            View view = inflater.inflate(R.layout.item_tablayout, null);            ImageView imageView = (ImageView) view.findViewById(R.id.tablayout_imageview);            TextView textView = (TextView) view.findViewById(R.id.tablayout_textview);            imageView.setBackground(getResources().getDrawable(drawables[i]));            textView.setText(texts[i]);            textView.setTextColor(getResources().getColorStateList(R.color.tablayout_color_selector));            tab.setCustomView(view);            if (i == 0) {                mTabLayout.addTab(tab, true);            } else {                mTabLayout.addTab(tab);            }        }        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {            @Override            public void onTabSelected(TabLayout.Tab tab) {                switch (tab.getPosition()) {                    case 0:                        Log.i("TAB", "TAB0");                        break;                    case 1:                        Log.i("TAB", "TAB1");                        break;                    case 2:                        Log.i("TAB", "TAB2");                        break;                    default:                        break;                }                showFragment(tab.getPosition());            }            @Override            public void onTabUnselected(TabLayout.Tab tab) {            }            @Override            public void onTabReselected(TabLayout.Tab tab) {            }        });        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff00ff"));        mTabLayout.setSelectedTabIndicatorHeight(0);    }

mTabLayout.addTab(tab, true);表示当前的tab为选定的状态;
showFragment(tab.getPosition());是一个根据所选tab切换内容的方法,页面的内容都是写在fragment里;
完整的代码如下所示:

package com.example.admin.superexample;import android.graphics.Color;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.support.design.widget.TabLayout;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.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView;import com.example.admin.superexample.fragment.NavigationFragment1;import com.example.admin.superexample.fragment.NavigationFragment2;import com.example.admin.superexample.fragment.NavigationFragment3;import java.util.ArrayList;import java.util.List;import butterknife.BindView;import butterknife.ButterKnife;public class NavigationActivity extends FragmentActivity {    @BindView(R.id.fragmen_content)    RelativeLayout mFragmentContent;    @BindView(R.id.tabLayout)    TabLayout mTabLayout;    // 三个用于切换的fragment    private NavigationFragment1 fragment1;    private NavigationFragment2 fragment2;    private NavigationFragment3 fragment3;    // fragment管理器    private FragmentManager fm;    // fragment事务    private FragmentTransaction ft;    // 所有fragment的集合    private List<Fragment> fragments;    // 当前页面所显示的fragment    private Fragment mCurrentFragment;    // 当前所选择的tab的位置编号    private int mCurrentTabPosition = -1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        /**         * 已经在style里面隐藏ActionBar和状态栏了,启用了Toolbar,所以此处代码注释         */        //        requestWindowFeature(Window.FEATURE_NO_TITLE);        //        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,        //                WindowManager.LayoutParams.FLAG_FULLSCREEN);        setContentView(R.layout.activity_navigation);        // 绑定BUtterKnife        ButterKnife.bind(this);        fragment1 = new NavigationFragment1();        fragment2 = new NavigationFragment2();        fragment3 = new NavigationFragment3();        fm = getSupportFragmentManager();        fragments = new ArrayList<Fragment>();        fragments.add(fragment1);        fragments.add(fragment2);        fragments.add(fragment3);        // 展示第一个fragment        showFragment(0);        // 启用系统自带tab布局的TabLayout        initTabLayout();        // 启用自定义tab布局的TabLayout        initTabLayoutForCustom();    }    private void initTabLayout() {        mTabLayout.addTab(mTabLayout.newTab().setText("消息")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector1)));        mTabLayout.addTab(mTabLayout.newTab().setText("联系人")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector2)), true);        mTabLayout.addTab(mTabLayout.newTab().setText("动态")                .setIcon(getResources().getDrawable(R.drawable.tablayout_selector3)));        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {            @Override            public void onTabSelected(TabLayout.Tab tab) {                // TODO 当tab被选择时调用                // 根据tab.getPosition()获取tab的位置            }            @Override            public void onTabUnselected(TabLayout.Tab tab) {                // TODO 当tab退出所选状态时调用                // 根据tab.getPosition()获取tab的位置            }            @Override            public void onTabReselected(TabLayout.Tab tab) {                // TODO 当tab被重复选择时调用                // 根据tab.getPosition()获取tab的位置            }        });        // 设置指示器的颜色        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff00ff"));        // 设置指示器的高度,设置为0则不显示指示器        mTabLayout.setSelectedTabIndicatorHeight(0);        /**         * 设置Tab在未选中和选中状态下的字体颜色,参数必须要传入表示颜色的int值,传入资源文件表示的int怎无效;         * 例如:mTableLayout.setTabTextColors(android.R.color.darker_gray, android.R.color.holo_blue_bright)无效;         * mTableLayout.setTabTextColors(getResources().getColor(android.R.color.darker_gray), getResources().getColor(android.R.color.holo_blue_bright))有效;         * mTableLayout.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#ff00ff"));传入的也是表示颜色的int值;         */        mTabLayout.setTabTextColors(getResources().getColor(android.R.color.darker_gray),                getResources().getColor(android.R.color.holo_blue_bright));        // 设置整个tabLayout的背景图片        Drawable drawable = getResources().getDrawable(R.drawable.bg);        drawable.setAlpha(100);        mTabLayout.setBackground(drawable);        // 当tab比较多的时候可以通过以下的代码来设置TabLayout是可以滑动的        //        mTableLayout.setTabMode(TabLayout.MODE_SCROLLABLE);    }    /**     * 加载自定义布局的TabLayout     */    private void initTabLayoutForCustom() {        LayoutInflater inflater = LayoutInflater.from(this);        int[] drawables = new int[]{R.drawable.tablayout_selector1, R.drawable.tablayout_selector2, R.drawable.tablayout_selector3};        final String[] texts = new String[]{"消息", "联系人", "动态"};        for (int i = 0; i < 3; i++) {            TabLayout.Tab tab = mTabLayout.newTab();            View view = inflater.inflate(R.layout.item_tablayout, null);            ImageView imageView = (ImageView) view.findViewById(R.id.tablayout_imageview);            TextView textView = (TextView) view.findViewById(R.id.tablayout_textview);            imageView.setBackground(getResources().getDrawable(drawables[i]));            textView.setText(texts[i]);            textView.setTextColor(getResources().getColorStateList(R.color.tablayout_color_selector));            tab.setCustomView(view);            if (i == 0) {                mTabLayout.addTab(tab, true);            } else {                mTabLayout.addTab(tab);            }        }        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {            @Override            public void onTabSelected(TabLayout.Tab tab) {                switch (tab.getPosition()) {                    case 0:                        Log.i("TAB", "TAB0");                        break;                    case 1:                        Log.i("TAB", "TAB1");                        break;                    case 2:                        Log.i("TAB", "TAB2");                        break;                    default:                        break;                }                showFragment(tab.getPosition());            }            @Override            public void onTabUnselected(TabLayout.Tab tab) {            }            @Override            public void onTabReselected(TabLayout.Tab tab) {            }        });        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff00ff"));        mTabLayout.setSelectedTabIndicatorHeight(0);    }    /**     * 根据点击的Tab来切换内容区域的fragmentr     * 本来自己也写了切换fragment的方法,但是看网上这个方法比较好所以就借用了     *     * @param position     */    public void showFragment(int position) {        if (!(position == mCurrentTabPosition)) {            // 每次操作都需要开启一个事务            ft = fm.beginTransaction();            if (mCurrentFragment != null) {                ft.hide(mCurrentFragment);            }            Fragment fragment = fm.findFragmentByTag(fragments.get(position).getClass().getName());            if (fragment == null) {                // 如fragment为空,则之前未添加此Fragment。便从集合中取出                fragment = fragments.get(position);            }            mCurrentFragment = fragment;            mCurrentTabPosition = position;            if (!fragment.isAdded()) {                ft.add(R.id.fragmen_content, fragment, fragment.getClass().getName());            } else {                ft.show(fragment);            }            ft.commit();        }    }}


以前写的博客比较说,所以可能在语言组织上和页面编辑上有很大的不足,可能会给大家在阅读和理解上造成一些不便希望大家谅解;
从事编程工作还没多久所以可能存在较多的错误或者不足,也希望大家能及时的指正这样也能帮助我的进步;
写博客记录学习与工作之中的一些知识和遇到的问题是一件很值得做的事,可以方便自己温故而知新个方便自己加深理解方便与他人交流;







阅读全文
0 0
原创粉丝点击