主要关键类:
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class HomeIndexVPAdapter extends FragmentPagerAdapter {
private List<EmphasisIndexBean> indexBeans;
private Context context;
private String dealDate;
private String year;
private String isManual;
private TargetFragment currentFragment;
public String TAB_TITLE="tabTitle";
private Map<String,Fragment> fragments=new HashMap<>();
private List<String> titles=new ArrayList<>();
private List<EmphasisIndexBean> selectedBeans=new ArrayList<>();
private int id=1;
private Map<String,Integer> IdsMap=new HashMap<>();
private List<String> preIds=new ArrayList<>();
public HomeIndexVPAdapter(@NonNull FragmentManager fm, List<EmphasisIndexBean> indexBeans, Context context,String dealDate,String year,String isManual) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.isManual=isManual;
this.indexBeans=indexBeans;
this.context=context;
this.dealDate=dealDate;
this.year=year;
IdsMap.clear();
preIds.clear();
titles.clear();
fragments.clear();
for (int i = 0; i < indexBeans.size(); i++) {
if ("1".equals(indexBeans.get(i).getIsShow())){//如果自定义展示,才展示
titles.add(indexBeans.get(i).getIndexName());
selectedBeans.add(indexBeans.get(i));
if(!IdsMap.containsKey(indexBeans.get(i).getIndexName())){//刷新判断是否有新增标题
IdsMap.put(indexBeans.get(i).getIndexName(),id++);//这里对应fragment,当tab被删减时,这里不用删减,fragment也一样
}
fragments .put(indexBeans.get(i).getIndexName(),getFragment(indexBeans.get(i))) ;//到时候数据拿下来后,可以在这里传入数据,或者看看还有没有别的办法可以传入
}
}
}
private Fragment getFragment(EmphasisIndexBean indexBean){
TargetFragment fragment=new TargetFragment();
Bundle bundle=new Bundle();
bundle.putSerializable("indexBean",indexBean);
bundle.putString("dealDate",dealDate);
bundle.putString("year",year);
bundle.putString("isManual",isManual);
fragment.setArguments(bundle);
return fragment;
}
@NonNull
@Override
public Fragment getItem(int position) {
/*if (fragments.containsKey(selectedBeans.get(position).getIndexName())){
return fragments.get(getPageTitle(position));//返回对应的fragment
}else {
TargetFragment fragment=new TargetFragment(context, selectedBeans.get(position), dealDate, year,isManual);
fragments.put(selectedBeans.get(position).getIndexName(),fragment);
return fragment;
}*/
return fragments.get(getPageTitle(position));//返回对应的fragment
}
@Override
public int getCount() {
return titles!=null?titles.size():0;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles!=null?titles.get(position):super.getPageTitle(position);
}
@Override
public long getItemId(int position) {
return IdsMap.size()>0?IdsMap.get(getPageTitle(position)):super.getItemId(position);
}
@Override
public int getItemPosition(@NonNull Object object) {
TargetFragment fragment= (TargetFragment) object;
//String title=fragment.getTitle();
int preId = preIds.indexOf(fragment.getTitle());
int newId=-1;
int i=0;
int size=getCount();
for(;i<size;i++){
if(getPageTitle(i).equals(fragment.getTitle())){
newId=i;
break;
}
}
if(newId!=-1&&newId==preId){
// Log.i("zgh","title="+title+" POSITION_UNCHANGED");
return POSITION_UNCHANGED;
}
if(newId!=-1){
// Log.i("zgh","title="+title+" newId="+newId);
return newId;
}
// Log.i("zgh","title="+title+" POSITION_NONE");
return POSITION_NONE;
}
@Override
public void notifyDataSetChanged() {
titles.clear();
for(EmphasisIndexBean info:indexBeans){
if ("1".equals(info.getIsShow())){//如果自定义展示,才展示
titles.add(info.getIndexName());//跟tab同步重新更新title
if (!fragments.keySet().contains(info.getIndexName())){
fragments.put(info.getIndexName(),getFragment(info));
}
if(!IdsMap.containsKey(info.getIndexName())){//刷新判断是否有新增标题
IdsMap.put(info.getIndexName(),id++);//这里对应fragment,当tab被删减时,这里不用删减,fragment也一样
}
}else {
if (fragments.keySet().contains(info.getIndexName())){
fragments.remove(info.getIndexName());
}
if (IdsMap.containsKey(info.getIndexName())){
IdsMap.remove(info.getIndexName());
}
}
}
super.notifyDataSetChanged();
preIds.clear();
int size=getCount();
for(int i=0;i<size;i++){
preIds.add((String) getPageTitle(i));
}
}
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
currentFragment= (TargetFragment) object;
super.setPrimaryItem(container, position, object);
}
/**
* 获取当前展示fragment实例
* @return
*/
public TargetFragment getCurrentFragment(){
return currentFragment;
}
}
使用:
private void initTabFragment() {
tabBeans.clear();
tabTitles.clear();
if (vpAdapter != null) {
vpAdapter = null;
}
for (int i = 0; i < indexBeans.size(); i++) {
if ("1".equals(indexBeans.get(i).getIsShow())) {//如果自定义展示,才展示
tabTitles.add(indexBeans.get(i).getIndexName());
tabBeans.add(indexBeans.get(i));
}
}
tabTarget.setTabMode(TabLayout.MODE_SCROLLABLE);//这里要特别注意下,如果tab超出了屏幕宽度,设置成fixed,那么tab就不会显示
//设置监听改变选中字体样式
tabTarget.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
selectedTab(tab);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
View view = tab.getCustomView();
if (null != view && view instanceof TextView) {
// 改变 tab 未选择状态下的字体大小
((TextView) view).setTextSize(15);
// 改变 tab 未选择状态下的字体颜色
((TextView) view).setTextColor(ContextCompat.getColor(context, R.color.tab_nuselect));
((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));//设置加粗
//((TextView) view).setCompoundDrawables(null,null,null, null);
ViewUtil.setTViewDrawable(((TextView) view), R.drawable.ic_tab_unselect, ViewUtil.BOTTOM);
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
//selectedTab(tab);
}
});
vpAdapter = new HomeIndexVPAdapter(getChildFragmentManager(), indexBeans, context, dealDate, year, isManual);
vpTargetInfo.setOffscreenPageLimit(indexBeans.size());//----------------------------------------------------------------------------------------------------------
vpTargetInfo.setAdapter(vpAdapter);
tabTarget.setupWithViewPager(vpTargetInfo);
setTabItem();
if ((!TextUtils.isEmpty(selectIndexDay) && UserConstant.dateType == 1) | (!TextUtils.isEmpty(selectIndexMon) && UserConstant.dateType == 2)) {//缓存选中的重点指标
for (int i = 0; i < tabBeans.size(); i++) {
if (selectIndexDay.equals(tabBeans.get(i).getIndexId()) | selectIndexMon.equals(tabBeans.get(i).getIndexId())) {
tabTarget.getTabAt(i).select();//默认选中第一个
selectedTab(tabTarget.getTabAt(tabTarget.getSelectedTabPosition()));//选中
}
}
} else {
if (tabTarget.getTabCount() > 0) {
tabTarget.getTabAt(0).select();//默认选中第一个
selectedTab(tabTarget.getTabAt(tabTarget.getSelectedTabPosition()));//选中
}
}
}
/**
* 设置tab的item样式
*/
private void setTabItem() {
for (int i = 0; i < tabTitles.size(); i++) {
//tl_video_section.addTab(tl_video_section.newTab());//这样写会出现item数目多出一倍,下面才是正确写法
//tabTarget.addTab(tabTarget.newTab());//得跟removeAllTabs一起使用
TabLayout.Tab tab = tabTarget.getTabAt(i);
if (tab != null) {
tab.setCustomView(ViewUtil.getTabView(context, i, tabTitles));
}
}
}
/**
* 选中改变样式
*
* @param tab
*/
private void selectedTab(TabLayout.Tab tab) {
// 获取 tab 组件
View view = tab.getCustomView();
if (null != view && view instanceof TextView) {
// 改变 tab 选择状态下的字体大小
((TextView) view).setTextSize(16);
// 改变 tab 选择状态下的字体颜色
((TextView) view).setTextColor(ContextCompat.getColor(context, R.color.text_black));
((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//设置加粗
ViewUtil.setTViewDrawable(((TextView) view), R.drawable.ic_tab_select, ViewUtil.BOTTOM);
}
}