1、問題描述 |
PagerSlidingTabStrip是android開源項目,指示器控件。官網地址:https://github.com/astuetz/PagerSlidingTabStripandroid
該組件可和ViewPager結合實現效果不錯的滑動式導航,最大特色是滑動條可跟隨ViewPager聯動,不過PagerSlidingTabStrip只有文字或圖片兩種,沒有提供圖片和文字的混合的形式,感受更適合實現頭部的導航,不太適合作底部導航(通常底部導航都是典型的上圖下字的導航),不過能夠經過修改源碼來實現這種圖文混合的導航,下面就使用ViewPager+PagerSlidingTabStrip實現如圖所示效果:git
2、修改PagerSlidingTabStrip組件 |
PagerSlidingTabStrip提供文本指示器和圖標指示器兩種,即 tab 是 text 仍是 icon。若是是 icon 的話,經過 Viewpager 的 adapter 實現接口IconTabProvider重寫getPageIconResId方法:github
public class MainPagerAdapter extends FragmentPagerAdapter implements IconTabProvider{ @Override public int getPageIconResId(int position){ … } }
若是是Text的話,只需重寫適配器自身的getPageTitle()方法:web
public class MainPagerAdapter extends FragmentPagerAdapter { @Override public int getPageTitle (int position){ … } }
這裏咱們還須要圖文混排的指示器(底部導航須要),所以在源碼作以下改動:ide
定義接口:佈局
public interface ViewTabProvider{ public View getTabView(int position); }
定義屬性和set/get方法字體
private String[] tabTexts;//存儲全部指示器的文本內容 private int normalIconRes[];//存儲全部指示器未選擇的圖標 private int lightIconRes[];//存儲全部指示器已選擇的圖標 修改notifyDataSetChanged()方法(紅色部分爲更改代碼): for (int i = 0; i < tabCount; i++) { if (pager.getAdapter() instanceof IconTabProvider) { addIconTab(i, ((IconTabProvider) pager.getAdapter()) .getPageIconResId(i)); } else if(pager.getAdapter() instanceof ViewTabProvider){ addViewTab(i, ((ViewTabProvider)pager.getAdapter()).getTabView(i)); }else { addTextTab(i, pager.getAdapter().getPageTitle(i).toString()); } }
添加addViewTab()方法:實現將tab添加到指示器中,併爲tab註冊單擊事件,當單擊tab時ViewPager翻頁,並調用updateTabStyles()更新Tab的樣式ui
private int currentIdx=0;//記錄當前指示器的索引值 private void addViewTab(final int position, View tab){ tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); currentIdx=position; updateTabStyles(); } }); tab.setPadding(tabPadding, 0, tabPadding, 0); tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); }
添加setSelectedTextColor()以便設置已選擇指示器的字體顏色this
private int tabSelectedTextColor;//表示已選擇的文本字體顏色 public void setSelectedTextColor(int color){ this.tabSelectedTextColor=color; updateTabStyles(); }
修改updateTabStyles()方法,紅色部分爲變動代碼spa
if (v instance of TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); if(i==0 && tabSelectedTextColor!=0){ tab.setTextColor(tabSelectedTextColor); } if (textAllCaps) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString().toUpperCase(locale)); } } }else if(v instanceof ViewGroup){ ImageView tabIcon=(ImageView)v.findViewById(android.R.id.icon); TextView tabTxt=(TextView)v.findViewById(android.R.id.title); tabTxt.setText(tabTexts[i]); if(currentIdx==i){ tabIcon.setImageResource(this.lightIconRes[i]); tabTxt.setTextColor(tabSelectedTextColor); }else{ tabTxt.setTextColor(tabTextColor); tabIcon.setImageResource(this.normalIconRes[i]); } } }
3、MainActivity部分,實現外層底部導航 |
一、MainActivity佈局文件,指示器在底部
<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" tools:context=".MainActivity" > <com.example.pagerslidingtabscripdemo.view.MyViewPager android:id="@+id/newsPager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/newsTabs" /> <com.astuetz.PagerSlidingTabStrip android:id="@+id/newsTabs" android:layout_width="match_parent" android:layout_height="48dp" android:background="@drawable/backgroud_tabs" android:layout_alignParentBottom="true" /> </RelativeLayout>
二、重寫ViewPager方法,實現禁止ViewPager滑動
public class MyViewPager extends ViewPager { private boolean isPagingEnable=true; public MyViewPager(Context context,AttributeSet attrs) { super(context,attrs); } public MyViewPager(Context context){ super(context); } @Override public boolean onTouchEvent(MotionEvent event){ return this.isPagingEnable&&super.onTouchEvent(event); } @Override public boolean onInterceptTouchEvent(MotionEvent event){ return this.isPagingEnable&&super.onInterceptTouchEvent(event); } public void setPagingEnabled(boolean enable){ this.isPagingEnable=enable; } }
三、MainActivity代碼:
private PagerSlidingTabStrip tabs; private MyViewPager pages; private List<Fragment> fragmentList; private MainPagerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabs=(PagerSlidingTabStrip)super.findViewById(R.id.newsTabs); pages=(MyViewPager)super.findViewById(R.id.newsPager); fragmentList=new ArrayList<Fragment>(); initView(); } private void initView(){ initFragment(); adapter=new MainPagerAdapter(super.getSupportFragmentManager(), fragmentList, this); pages.setAdapter(adapter); pages.setPagingEnabled(false); tabs.setNormalIconRes(TabsData.normalIconRes);//設置未選擇的圖標 tabs.setLightIconRes(TabsData.lightIconRes);//設置已選擇的圖標 tabs.setTabTexts(TabsData.boards);//設置文本 tabs.setViewPager(pages);//與ViewPager關聯,這樣指示器就能夠和ViewPager聯動 tabs.setSelectedTextColor(Color.RED);//設置當前選擇的tab的文本顏色 tabs.setIndicatorColor(Color.TRANSPARENT);//去除指示器的底部橫線 tabs.setDividerColor(Color.TRANSPARENT);//去除tab間的分割線 } private void initFragment(){ fragmentList=new ArrayList<Fragment>(); fragmentList.add(new NewsFragment()); for(int i=1;i<TabsData.boards.length;i++){ Bundle bundle=new Bundle(); bundle.putString("title", TabsData.boards[i]); CommentFragment fragment=new CommentFragment(); fragment.setArguments(bundle); fragmentList.add(fragment); } }
四、TabsData數據:
public class TabsData { public static String[] boards={"新聞","閱讀","試聽","發現"," 我"}; public static int[] normalIconRes={R.drawable.foot_news_normal, R.drawable.foot_read_normal,R.drawable.foot_vdio_normal,R.drawable.foot_fond_normal,R.drawable.foot_out_normal}; Public static int[] lightIconRes={R.drawable.foot_news_light, R.drawable.foot_read_light,R.drawable.foot_vdio_light, R.drawable.foot_found_light,R.drawable.foot_out_light}; }
五、MainPagerAdapter適配器:
public class MainPagerAdapter extends FragmentPagerAdapter implements ViewTabProvider { private List<Fragment> fragmentList; private Context context; public MainPagerAdapter(FragmentManager fm,List<Fragment> fragmentList,Context context) { super(fm); this.fragmentList=fragmentList; this.context=context; } @Override public Fragment getItem(int arg0) { return fragmentList.get(arg0); } @Override public int getCount() { return fragmentList.size(); } @Override public View getTabView(int position) { View view=LayoutInflater.from(context).inflate(R.layout.footer_tabs, null); return view; } }
六、CommentFragment代碼:
public class CommentFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView tvTitle=new TextView(super.getActivity()); tvTitle.setText(title); tvTitle.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); tvTitle.setGravity(Gravity.CENTER); tvTitle.setTextSize(20); return tvTitle; } private String title; @Override public void setArguments(Bundle bundle) { title=bundle.getString("title"); } }
4、NewsFragment 實現內層頭部導航 |
一、Xml文件:
<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" tools:context=".MainActivity" > <com.astuetz.PagerSlidingTabStrip android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="48dp" android:background="@drawable/backgroud_tabs" /> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout>
注意:fragment中使用PagerSlidingTabStrip組件須採用LinearLayout佈局,不能使用相對佈局
二、代碼:
public class NewsFragment extends Fragment { @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(view==null){ view=inflater.inflate(R.layout.news_fragment, null); ViewPager pages=(ViewPager)view.findViewById(R.id.pager); PagerSlidingTabStrip tabs=(PagerSlidingTabStrip)view.findViewById(R.id.tabs); initFragment(); adapter=new ChannelPagerAdapter(super.getActivity().getSupportFragmentManager(), fragmentList, titles); pages.setAdapter(adapter); tabs.setViewPager(pages); tabs.setSelectedTextColor(Color.RED); tabs.setDividerColor(Color.TRANSPARENT); tabs.setIndicatorColor(Color.RED); } ViewGroup parent=(ViewGroup)view.getParent(); if(parent!=null){ parent.removeView(view); } return view; } private ChannelPagerAdapter adapter; private List<Fragment> fragmentList; private String[] titles={"頭條","娛樂","體育","財經","熱點","科技"}; private void initFragment(){ Fragment fragment=null; fragmentList=new ArrayList<Fragment>(); for(String title: titles){ fragment=new ChannelNewsFragment(); Bundle bundle=new Bundle(); bundle.putString("title",title); fragment.setArguments(bundle); fragmentList.add(fragment); } } }
三、 ChannelNewsFragment
public class ChannelNewsFragment extends Fragment { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void onAttach(Activity activity) { super.onAttach(activity); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView tvTitle=new TextView(super.getActivity()); tvTitle.setText(title); tvTitle.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); tvTitle.setGravity(Gravity.CENTER); tvTitle.setTextSize(20); return tvTitle; } private String title; public void setArguments(Bundle bundle) { title=bundle.getString("title"); } }