不得不说,看大神写的代码是一种享受。学习开源中国的首页架构,解耦手法叹为观止,真是让小白受用。之前在guthub上学习了一套首页构造的开源项目,用起来确实很方便,可是,在实际开发中,我希望当我第一次点击底部tab按钮时,才创建对应的fragment。这是一个很正常的需求,而我之前写的一篇文章利用开源框架实现首页的视图框架搭建,这个框架是每次点击进入app,所有底部按钮对应的frament,全都被new出来了,这个很头疼。所以,我又学习了开源中国代码,经过分析,发现他这可以满足这个需求,而且纯手工,并且解耦得非常棒。故此分享。
效果图:
新建一个MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.dingfang.org.navbardemo.fragment.NavFragment;
import com.dingfang.org.navbardemo.view.NavigationButton;
public class MainActivity extends AppCompatActivity implements NavFragment.OnNavigationReselectListener{
private NavFragment mNavBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
mNavBar = ((NavFragment) manager.findFragmentById(R.id.nav_bar));
mNavBar.setup(this, manager, R.id.main_container, this);
}
@Override
public void onReselect(NavigationButton navigationButton) {
Fragment fragment = navigationButton.getFragment();
if (fragment != null) {
//do your business
}
}
}
以及activity_main.xml
第一眼看不明白的代码,没关系,先放在一边,后面就会一一列出来了。
很明显,其底部的tab是承载在fragment里面的,这里,我们新建NavFragment.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dingfang.org.navbardemo.R;
import com.dingfang.org.navbardemo.view.NavigationButton;
import java.util.List;
public class NavFragment extends Fragment implements View.OnClickListener {
NavigationButton mNavNews;
NavigationButton mNavTweet;
NavigationButton mNavExplore;
NavigationButton mNavMe;
View root;
private Context mContext;
private int mContainerId;
private FragmentManager mFragmentManager;
private NavigationButton mCurrentNavButton;
private OnNavigationReselectListener mOnNavigationReselectListener;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_nav, container, false);
initView();
return root;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData();
}
/**
* 初始化视图数据
*/
private void initData() {
mNavNews.init(R.drawable.tab_icon_new, "综合", Frament01.class);
mNavNews.setOnClickListener(this);
mNavTweet.init(R.drawable.tab_icon_tweet, "动态", Frament02.class);
mNavTweet.setOnClickListener(this);
mNavExplore.init(R.drawable.tab_icon_explore, "发现", Frament03.class);
mNavExplore.setOnClickListener(this);
mNavMe.init(R.drawable.tab_icon_me, "我的", Frament04.class);
mNavMe.setOnClickListener(this);
}
/**
* 全局初始化
*/
private void initView() {
mNavNews = (NavigationButton) root.findViewById(R.id.nav_item_news);
mNavTweet = (NavigationButton) root.findViewById(R.id.nav_item_tweet);
mNavExplore = (NavigationButton) root.findViewById(R.id.nav_item_explore);
mNavMe = (NavigationButton) root.findViewById(R.id.nav_item_me);
}
/**
* 初始化
* @param context
* @param fragmentManager
* @param contentId
* @param listener
*/
public void setup(Context context, FragmentManager fragmentManager, int contentId, OnNavigationReselectListener listener) {
mContext = context;
mFragmentManager = fragmentManager;
mContainerId = contentId;
mOnNavigationReselectListener = listener;
// do clear
clearOldFragment();
// do select first
doSelect(mNavNews);
}
/**
* 以防万一,清除一遍fragment
*/
@SuppressWarnings("RestrictedApi")
private void clearOldFragment() {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
List fragments = mFragmentManager.getFragments();
if (transaction == null || fragments == null || fragments.size() == 0)
return;
boolean doCommit = false;
for (Fragment fragment : fragments) {
if (fragment != this && fragment != null) {
transaction.remove(fragment);
doCommit = true;
}
}
if (doCommit)
transaction.commitNow();
}
/**
* tab 切换
* @param newNavButton
*/
private void doSelect(NavigationButton newNavButton) {
// If the new navigation is me info fragment, we intercept it
/*
if (newNavButton == mNavMe) {
if (interceptMessageSkip())
return;
}
*/
NavigationButton oldNavButton = null;
if (mCurrentNavButton != null) {
oldNavButton = mCurrentNavButton;
if (oldNavButton == newNavButton) {
onReselect(oldNavButton);
return;
}
oldNavButton.setSelected(false);
}
newNavButton.setSelected(true);
doTabChanged(oldNavButton, newNavButton);
mCurrentNavButton = newNavButton;
}
/**
* fragment切换
* 该方法,保证了,使用只有一个fragment与activity绑定
* 在fragment不存在的时候,就创建,存在的时候,就绑定
* @param oldNavButton
* @param newNavButton
*/
private void doTabChanged(NavigationButton oldNavButton, NavigationButton newNavButton) {
FragmentTransaction ft = mFragmentManager.beginTransaction();
if (oldNavButton != null) {
if (oldNavButton.getFragment() != null) {
ft.detach(oldNavButton.getFragment());//Fragment实例还在,只是解除了与activity的绑定
}
}
if (newNavButton != null) {
if (newNavButton.getFragment() == null) {
//切换的时候,如果fragment存在,就切换,不存在,就创建
Fragment fragment = Fragment.instantiate(mContext,
newNavButton.getClx().getName(), null);
ft.add(mContainerId, fragment, newNavButton.getTag());
newNavButton.setFragment(fragment);
} else {
ft.attach(newNavButton.getFragment());
}
}
ft.commit();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nav_item_explore:
Toast.makeText(mContext, "nav_item_explore", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_item_news:
Toast.makeText(mContext, "nav_item_news", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_item_me:
Toast.makeText(mContext, "nav_item_me", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_item_tweet:
Toast.makeText(mContext, "nav_item_tweet", Toast.LENGTH_SHORT).show();
break;
}
if (view instanceof NavigationButton) {
NavigationButton nav = (NavigationButton) view;
doSelect(nav);
}
}
public interface OnNavigationReselectListener {
void onReselect(NavigationButton navigationButton);
}
private void onReselect(NavigationButton navigationButton) {
if (mOnNavigationReselectListener != null) {
mOnNavigationReselectListener.onReselect(navigationButton);
}
}
}
这个类,是本篇的精华,大多数关键地方都做了注释,可以看到,这个NavFragment碎片的onCreateView方法中返回了一个视图onCreateView.xml,其结构如下:
布局效果如下图:
由布局文件可以看到,这里的tab支持消息tag,就是那个红色部分,显示消息数量。在xml文件中可以看出有个NavigationButton自定义类,其代码如下:
package com.dingfang.org.navbardemo.view;
import android.content.Context;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.RequiresApi;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.dingfang.org.navbardemo.R;
/**
* 底部切换按钮
*/
public class NavigationButton extends FrameLayout {
private Fragment mFragment = null;
private Class> mClx;
private ImageView mIconView;
private TextView mTitleView;
private TextView mDot;
private String mTag;
public NavigationButton(Context context) {
super(context);
init();
}
public NavigationButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NavigationButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public NavigationButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.layout_nav_item, this, true);
mIconView = (ImageView) findViewById(R.id.nav_iv_icon);
mTitleView = (TextView) findViewById(R.id.nav_tv_title);
mDot = (TextView) findViewById(R.id.nav_tv_dot);
}
public void setSelected(boolean selected) {
super.setSelected(selected);
mIconView.setSelected(selected);
mTitleView.setSelected(selected);
}
public void showRedDot(int count) {
mDot.setVisibility(count > 0 ? VISIBLE : GONE);
mDot.setText(String.valueOf(count));
}
public void init(@DrawableRes int resId, @StringRes int strId, Class> clx) {
mIconView.setImageResource(resId);
mTitleView.setText(strId);
mClx = clx;
mTag = mClx.getName();
}
public void init(@DrawableRes int resId, String strId, Class> clx) {
mIconView.setImageResource(resId);
mTitleView.setText(strId);
mClx = clx;
mTag = mClx.getName();
}
public Class> getClx() {
return mClx;
}
public Fragment getFragment() {
return mFragment;
}
public void setFragment(Fragment fragment) {
this.mFragment = fragment;
}
public String getTag() {
return mTag;
}
}
其中在初始化时
private void init() {
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.layout_nav_item, this, true);
mIconView = (ImageView) findViewById(R.id.nav_iv_icon);
mTitleView = (TextView) findViewById(R.id.nav_tv_title);
mDot = (TextView) findViewById(R.id.nav_tv_dot);
}
layout_nav_item.xml文件如下:
看布局文件,有几个样式相关的xml文件,这里列举部分如tab_icon_new.xml
primarybar_txt.xml
代码实现的大致就是这样,需要源码的同学点击这里