碎片实现多个页签切换

来源:互联网 发布:软件为什么需要预约 编辑:程序博客网 时间:2024/05/17 07:07

                              实现主页面多个标签页切换

在这里实现了4个标签页的切换,比较简单且稳定的实现方式,容易理解,先上效果图:

                     

页面很简单,连按钮都是一样的,手太懒了,要不是需要两个图片,我就用ic_launch了

下面4个是切换按钮,几个都一样,根据需求随意删加即可,上面的大白页就是我们的Fragment了,需要的话就在上面弄布局,自定义的BottomBar很好理解,基本常识,废话少说上代码(用的话复制粘贴简单修改就OK,我也会上传源码):

   1.MainActivity(用来放置BottomBar控件和碎片),最下面那个方法是用来检测按两次返回键退出应用的,不需要的直接删了就行:

package com.thecanteensoftware.activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v7.app.AppCompatActivity;import android.view.KeyEvent;import android.widget.LinearLayout;import com.thecanteensoftware.R;import com.thecanteensoftware.frg.MainFragment;import com.thecanteensoftware.frg.MineFragment;import com.thecanteensoftware.frg.RecommendFragment;import com.thecanteensoftware.frg.ShoppingCartFragment;import com.thecanteensoftware.util.UtilToast;import com.thecanteensoftware.view.BottomBar;import com.thecanteensoftware.view.BottomBarTab;import java.util.Timer;import java.util.TimerTask;public class MainActivity extends AppCompatActivity {    /**     * 4个页面碎片     */    private MainFragment mainFragment;    private MineFragment mineFragment;    private RecommendFragment recommendFragment;    private ShoppingCartFragment shoppingCartFragment;    private FragmentManager fragmentManager;    private LinearLayout mainContainer;    private BottomBar bottomBar;    private Fragment fragment;    int clickBackCount = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        barListener();    }    public void initView(){        mainContainer = (LinearLayout) findViewById(R.id.main_container);        bottomBar = (BottomBar) findViewById(R.id.bottomBar);        /**         * 第二个参数是选中后显示的图片,第三个是未选中时的图片,第四个是页面名字         */        BottomBarTab bottomBarTab0 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "菜单");        BottomBarTab bottomBarTab1 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "推荐");        BottomBarTab bottomBarTab2 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "购物车");        BottomBarTab bottomBarTab3 = new BottomBarTab(this, R.mipmap.category_, R.mipmap.category, "我的");        bottomBar.addItem(bottomBarTab0);        bottomBar.addItem(bottomBarTab1);        bottomBar.addItem(bottomBarTab2);        bottomBar.addItem(bottomBarTab3);        fragmentManager = getSupportFragmentManager();    }    /**     * 填充按钮上方Framgment布局     */    public void barListener(){        bottomBar.setListener(new BottomBar.OnTabItemClickListener() {                                  @Override                                  public void onClick(int position) {                                      switch (position) {                                          case 0:                                              if (mainFragment == null) {                                                  mainFragment = new MainFragment();                                                  getSupportFragmentManager().beginTransaction()                                                          .add(R.id                                                                  .main_container, mainFragment)                                                          .commit();                                              } else {                                                  if (fragment == null) {                                                      fragmentManager.beginTransaction().show                                                              (mainFragment).commit();                                                  } else {                                                      fragmentManager.beginTransaction().hide                                                              (fragment).show                                                              (mainFragment).commit();                                                  }                                              }                                              fragment = mainFragment;                                              break;                                          case 1:                                              if (recommendFragment == null) {                                                  recommendFragment = new RecommendFragment();                                                  fragmentManager.beginTransaction().add(R.id                                                                  .main_container,                                                          recommendFragment).commit();                                              }                                              fragmentManager.beginTransaction().hide(fragment)                                                      .show(recommendFragment)                                                      .commit();                                              fragment = recommendFragment;                                              break;                                          case 2:                                              if (shoppingCartFragment == null) {                                                  shoppingCartFragment = new ShoppingCartFragment();                                                  fragmentManager.beginTransaction().add(R.id                                                                  .main_container,                                                          shoppingCartFragment).commit();                                              }                                              fragmentManager.beginTransaction().hide(fragment)                                                      .show(shoppingCartFragment)                                                      .commit();                                              fragment = shoppingCartFragment;                                              break;                                          case 3:                                              if (mineFragment == null) {                                                  mineFragment = new MineFragment();                                                  fragmentManager.beginTransaction().add(R.id                                                                  .main_container,                                                          mineFragment).commit();                                              }                                              fragmentManager.beginTransaction().hide(fragment)                                                      .show(mineFragment)                                                      .commit();                                              fragment = mineFragment;                                              break;                                      }                                  }                              }        );        //默认选中标签页        bottomBar.setCurrentItem(0);    }    /**     * 按两次返回退出应用     * @param event     * @return     */    @Override    public boolean dispatchKeyEvent(KeyEvent event) {        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent                .ACTION_DOWN) {            switch (clickBackCount) {                case 0:                    clickBackCount++;                    // Crouton.makeText(mActivity,                    // getString(R.string.press_again_exit), Style.INFO,                    // R.id.bottom_layout).show();                    UtilToast.show(this, "再按一次退出");               /* 延时3秒执行将点击的次数归零 */                    new Timer().schedule(new TimerTask() {                        @Override                        public void run() {                            clickBackCount = 0;                        }                    }, 1500);                    break;                case 1:                    this.finish();                    System.exit(0);                    break;                default:                    break;            }            return true;        }        return super.dispatchKeyEvent(event);    }}

在上边退出的方法中还用到了一个工具类(我是为了方便以后项目才这样弄的,用不着的简单Toast就行):

package com.thecanteensoftware.util;import android.content.Context;import android.widget.Toast;public final class UtilToast {    private UtilToast() {    }    public static void show(Context context, CharSequence text) {        if(text != null && !text.toString().trim().equals("")) {            Toast.makeText(context, text, 0).show();        }    }    public static void show(Context context, int res) {        Toast.makeText(context, res, 0).show();    }}

   2.activity_main.xml布局(View只是一根分割线):

<?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="match_parent">    <LinearLayout        android:id="@+id/main_container"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_above="@+id/ll_bottombar"        android:elevation="-2dp"        android:orientation="vertical"></LinearLayout>    <LinearLayout        android:id="@+id/ll_bottombar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentStart="true"        android:orientation="vertical">        <View            android:layout_width="match_parent"            android:layout_height="1px"            android:background="@color/colorTab0"            />        <com.thecanteensoftware.view.BottomBar            android:id="@+id/bottomBar"            android:layout_width="match_parent"            android:layout_height="wrap_content">        </com.thecanteensoftware.view.BottomBar>    </LinearLayout></RelativeLayout>


   3.自定义BottomBar,用来存放切换按钮和监听按钮事件进行切换操作:

package com.thecanteensoftware.view;import android.content.Context;import android.graphics.Color;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;import android.widget.LinearLayout;/** * Created by Administrator on 6/15 0015. */public class BottomBar extends LinearLayout {    private LinearLayout mTabLayout;    private LayoutParams mTabParams;    private int mCurrentPosition = 0;    OnTabItemClickListener listener;    public void setListener(OnTabItemClickListener listener) {        this.listener = listener;    }    public BottomBar(Context context) {        this(context, null);    }    public BottomBar(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public BottomBar(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init(context);    }    private void init(Context context) {        setOrientation(VERTICAL);        mTabLayout = new LinearLayout(context);        mTabLayout.setBackgroundColor(Color.WHITE);        mTabLayout.setOrientation(LinearLayout.HORIZONTAL);        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);        mTabLayout.setLayoutParams(lp);        addView(mTabLayout);        mTabParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);        mTabParams.weight = 1;    }    /**     * 添加点击按钮     * @param tab     * @return     */    public BottomBar addItem(final BottomBarTab tab) {        tab.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View view) {                int position = tab.getTabPosition();                if (mCurrentPosition == position) {                } else {                    tab.setSelected(true);                    mTabLayout.getChildAt(mCurrentPosition).setSelected(false);                    mCurrentPosition = position;                    listener.onClick(position);                }            }        });        tab.setTabPosition(mTabLayout.getChildCount());        tab.setLayoutParams(mTabParams);        mTabLayout.addView(tab);        return this;    }    public interface OnTabItemClickListener{        public void onClick(int position);    }    /**     * @param position     */    public void setCurrentItem(int position) {        listener.onClick(position);    }}
   4.自定义BottomBarTab,切换按钮样式:

package com.thecanteensoftware.view;import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.support.annotation.DrawableRes;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.TextView;import com.thecanteensoftware.R;/** * Created by Administrator on 6/15 0015. * Tab样式设置 */public class BottomBarTab extends FrameLayout {    private ImageView mIcon;    private int  selectIcon,unSelectIcon; //图标选择    private int mTabPosition = -1;    private Context mContext;    public BottomBarTab(Context context, @DrawableRes int selectIcon, @DrawableRes int unSelectIcon, String text) {        this(context, null,  selectIcon,unSelectIcon,text);    }    public BottomBarTab(Context context, AttributeSet attrs, @DrawableRes int selectIcon, @DrawableRes int unSelectIcon, String text) {        this(context, attrs, 0, selectIcon,unSelectIcon,text);    }    public BottomBarTab(Context context, AttributeSet attrs, int defStyleAttr, @DrawableRes int selectIcon, @DrawableRes int unSelectIcon, String text) {        super(context, attrs, defStyleAttr);        init(context, selectIcon,unSelectIcon,text);    }    private void init(Context context, int  selectIcon, int unSelectIcon, String text) {        this.mContext = context;        this.selectIcon = selectIcon;        this.unSelectIcon = unSelectIcon;        TypedArray typedArray = context.obtainStyledAttributes(                new int[]{R.attr.selectableItemBackgroundBorderless});        Drawable drawable = typedArray.getDrawable(0);        setBackgroundDrawable(drawable);        typedArray.recycle();        View view = LayoutInflater.from(context).inflate(R.layout.activity_mian_bottom_item,null);        mIcon = (ImageView) view.findViewById(R.id.tab_image);        mIcon.setImageResource(unSelectIcon);        TextView textView = (TextView)view.findViewById(R.id.tab_text);        textView.setText(text);        addView(view);    }    @Override    public void setSelected(boolean selected) {        super.setSelected(selected);        if (selected) {            mIcon.setImageResource(selectIcon);        } else {            mIcon.setImageResource(unSelectIcon);        }    }    public void setTabPosition(int position) {        mTabPosition = position;        if (position == 0) {            setSelected(true);        }    }    public int getTabPosition() {        return mTabPosition;    }}
    5.activity_main_bottom_item.xml单个标签页布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:background="@color/colorWhite"    android:gravity="center_horizontal"    android:addStatesFromChildren="true"    android:layout_height="wrap_content">    <ImageView        android:id="@+id/tab_image"        android:layout_width="wrap_content"        android:layout_marginTop="4dp"        android:adjustViewBounds="true"        android:contentDescription="@null"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/tab_text"        android:gravity="center_horizontal|bottom"        android:padding="2dp"        android:layout_width="wrap_content"        android:textColor="@color/activity_main_bottom_item_text_selector"        android:layout_height="match_parent" /></LinearLayout>
    6.4个Fragment布局都是一样的,也没有别的东西,我就贴一个了:

package com.thecanteensoftware.frg;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.thecanteensoftware.R;/** * Created by Administrator on 2017/6/20 0020. */public class MainFragment extends Fragment{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.main_fragment, container, false);        return view;    }}
    7.然后是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">    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="1"        android:gravity="center"/></LinearLayout>
    8.activity_main_bottom_itme_text_selector.xml(这个新建一个color文件夹放进去,在上面activity_main_bottom_item.xml布局里面用到的)文字选择器:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:color="@color/colorTab" android:state_selected="true" />    <item android:color="@color/colorTab" android:state_pressed="true" />    <item android:color="@color/colorTab" android:state_checked="true" />    <item android:color="@color/colorTab0" /></selector>
    9.colors.xml添加了3个颜色:

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="colorPrimary">#3F51B5</color>    <color name="colorPrimaryDark">#303F9F</color>    <color name="colorAccent">#FF4081</color>    <color name="colorWhite">#FFFFFF</color>    <color name="colorTab">#007700</color>    <color name="colorTab0">#000000</color></resources>

基本上应该是可以了,图片的话自己找,换的话就是MainActivity里面,文字字体修改的话就是在color选择器里面,剩下的就是按需求来了,算是比较详细,也容易理解,谢谢大家!


手懒的童鞋来这里:源码在这里