您好,登錄后才能下訂單哦!
隨著時(shí)間的推移現(xiàn)在的軟件要求顯示的內(nèi)容越來越多,所以要在小的屏幕上能夠更好的顯示更多的內(nèi)容,首先我們會(huì)想到底部菜單欄,但是有時(shí)候像今日頭條新聞客戶端要顯示的內(nèi)容太多,而且又想在主界面全部顯示出來,所以有加了頂部導(dǎo)航欄。
今日頭條頂部導(dǎo)航欄區(qū)域的主要部分是一個(gè)導(dǎo)航菜單。導(dǎo)航菜單是一組標(biāo)簽的集合,在新聞客戶端中,每個(gè)標(biāo)簽標(biāo)示一個(gè)新聞?lì)悇e,對(duì)應(yīng)下面ViewPager控件的一個(gè)分頁面。當(dāng)用戶在ViewPager區(qū)域滑動(dòng)頁面時(shí),對(duì)應(yīng)的導(dǎo)航菜單標(biāo)簽也會(huì)相應(yīng)的被選中,選中的標(biāo)簽通過一個(gè)矩形紅框高亮顯示,紅框背景中的標(biāo)簽文字變?yōu)榘咨t框外的區(qū)域標(biāo)簽文字仍為灰色。當(dāng)用戶直接在導(dǎo)航菜單選中某個(gè)標(biāo)簽時(shí),ViewPager會(huì)自動(dòng)的切換到對(duì)應(yīng)的分頁面。在本文中導(dǎo)航菜單作為一個(gè)單獨(dú)的UI控件實(shí)現(xiàn),類名為CatagoryTabStrip,繼承自HorizontalScrollView,這樣就可以很容易的實(shí)現(xiàn)導(dǎo)航菜單的左右滑動(dòng)效果以及與下面ViewPager控件的聯(lián)動(dòng)。
先看一下實(shí)現(xiàn)的效果對(duì)比:
頂部導(dǎo)航欄區(qū)域和ViewPager區(qū)域View層次結(jié)構(gòu)
主界面布局
<RelativeLayout android:id="@+id/main_layout" android:background="@color/activity_bg_color" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <RelativeLayout android:id="@+id/title_bar" > <FrameLayout android:id="@+id/top_head_container" android:paddingLeft="10.0dip" android:paddingRight="10.0dip" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:layout_gravity="center_vertical" android:id="@+id/top_head" android:contentDescription="@string/app_name" android:background="@drawable/bg_head" android:src="@drawable/default_round_head" android:padding="2.0dip" android:layout_width="@dimen/head_size" android:layout_height="@dimen/head_size" android:scaleType="fitXY" /> </FrameLayout> <ImageView android:gravity="center" android:id="@+id/top_more" android:contentDescription="@string/app_name" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="12.0dip" android:src="@drawable/right_drawer" android:scaleType="centerInside" android:layout_alignParentRight="true" android:layout_centerVertical="true" /> <RelativeLayout android:id="@+id/title_click_layout" android:paddingLeft="13.0dip" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_centerInParent="true"> <FrameLayout android:id="@+id/title_parent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true"> <ImageView android:layout_gravity="center" android:id="@+id/title_recent" android:contentDescription="@string/app_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/title" /> </FrameLayout> <ImageView android:id="@+id/top_refresh" android:contentDescription="@string/app_name" android:padding="3.0dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/refreshicon_titlebar" android:layout_toRightOf="@id/title_parent" android:layout_centerVertical="true" /> </RelativeLayout> </RelativeLayout> <RelativeLayout android:id="@+id/category_layout" android:background="@drawable/bg_category_bar" android:layout_width="fill_parent" android:layout_height="@dimen/top_category_height" android:layout_below="@id/title_bar" > <ImageView android:id="@+id/icon_category" android:layout_width="@dimen/top_category_height" android:layout_height="@dimen/top_category_height" android:src="@drawable/ic_category_expand" android:contentDescription="@string/app_name" android:scaleType="center" android:layout_alignParentRight="true" android:layout_centerVertical="true" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="@dimen/top_category_height" android:layout_toLeftOf="@id/icon_category" android:layout_alignParentLeft="true" android:layout_centerVertical="true"> <com.rainsong.toutiaotabdemo.CategoryTabStrip android:id="@+id/category_strip" android:paddingLeft="6.0dip" android:paddingRight="6.0dip" android:clipToPadding="false" android:layout_width="wrap_content" android:layout_height="@dimen/top_category_height" /> </LinearLayout> </RelativeLayout> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/category_layout" /> </RelativeLayout>
在Activity中CatagoryTabStrip控件與ViewPager控件的聯(lián)合使用
MainActivity.java
package com.rainsong.toutiaotabdemo; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; public class MainActivity extends FragmentActivity { private CategoryTabStrip tabs; private ViewPager pager; private MyPagerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabs = (CategoryTabStrip) findViewById(R.id.category_strip); pager = (ViewPager) findViewById(R.id.view_pager); adapter = new MyPagerAdapter(getSupportFragmentManager()); pager.setAdapter(adapter); tabs.setViewPager(pager); } public class MyPagerAdapter extends FragmentPagerAdapter { private final List<String> catalogs = new ArrayList<String>(); public MyPagerAdapter(FragmentManager fm) { super(fm); catalogs.add(getString(R.string.category_hot)); catalogs.add("\u672c\u5730"); catalogs.add(getString(R.string.category_video)); catalogs.add(getString(R.string.category_society)); catalogs.add(getString(R.string.category_entertainment)); catalogs.add(getString(R.string.category_tech)); catalogs.add(getString(R.string.category_finance)); catalogs.add(getString(R.string.category_military)); catalogs.add(getString(R.string.category_world)); catalogs.add(getString(R.string.category_image_ppmm)); catalogs.add(getString(R.string.category_health)); catalogs.add(getString(R.string.category_government)); } @Override public CharSequence getPageTitle(int position) { return catalogs.get(position); } @Override public int getCount() { return catalogs.size(); } @Override public Fragment getItem(int position) { return NewsFragment.newInstance(position); } } }
CatagoryTabStrip控件的實(shí)現(xiàn)代碼
CategoryTabStrip.java
package com.rainsong.toutiaotabdemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; public class CategoryTabStrip extends HorizontalScrollView { private LayoutInflater mLayoutInflater; private final PageListener pageListener = new PageListener(); private ViewPager pager; private LinearLayout tabsContainer; private int tabCount; private int currentPosition = 0; private float currentPositionOffset = 0f; private Rect indicatorRect; private LinearLayout.LayoutParams defaultTabLayoutParams; private int scrollOffset = 10; private int lastScrollX = 0; private Drawable indicator; private TextDrawable[] drawables; private Drawable left_edge; private Drawable right_edge; public CategoryTabStrip(Context context) { this(context, null); } public CategoryTabStrip(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CategoryTabStrip(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mLayoutInflater = LayoutInflater.from(context); drawables = new TextDrawable[3]; int i = 0; while (i < drawables.length) { drawables[i] = new TextDrawable(getContext()); i++; } indicatorRect = new Rect(); setFillViewport(true); setWillNotDraw(false); // 標(biāo)簽容器 tabsContainer = new LinearLayout(context); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(tabsContainer); DisplayMetrics dm = getResources().getDisplayMetrics(); scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm); defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); // 繪制高亮區(qū)域作為滑動(dòng)分頁指示器 indicator = getResources().getDrawable(R.drawable.bg_category_indicator); // 左右邊界陰影效果 left_edge = getResources().getDrawable(R.drawable.ic_category_left_edge); right_edge = getResources().getDrawable(R.drawable.ic_category_right_edge); } // 綁定與CategoryTabStrip控件對(duì)應(yīng)的ViewPager控件,實(shí)現(xiàn)聯(lián)動(dòng) public void setViewPager(ViewPager pager) { this.pager = pager; if (pager.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } pager.setOnPageChangeListener(pageListener); notifyDataSetChanged(); } // 當(dāng)附加在ViewPager適配器上的數(shù)據(jù)發(fā)生變化時(shí),應(yīng)該調(diào)用該方法通知CategoryTabStrip刷新數(shù)據(jù) public void notifyDataSetChanged() { tabsContainer.removeAllViews(); tabCount = pager.getAdapter().getCount(); for (int i = 0; i < tabCount; i++) { addTab(i, pager.getAdapter().getPageTitle(i).toString()); } } // 添加一個(gè)標(biāo)簽到導(dǎo)航菜單 private void addTab(final int position, String title) { ViewGroup tab = (ViewGroup)mLayoutInflater.inflate(R.layout.category_tab, this, false); TextView category_text = (TextView) tab.findViewById(R.id.category_text); category_text.setText(title); category_text.setGravity(Gravity.CENTER); category_text.setSingleLine(); category_text.setFocusable(true); category_text.setTextColor(getResources().getColor(R.color.category_tab_text)); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); tabsContainer.addView(tab, position, defaultTabLayoutParams); } // 計(jì)算滑動(dòng)過程中矩形高亮區(qū)域的上下左右位置 private void calculateIndicatorRect(Rect rect) { ViewGroup currentTab = (ViewGroup)tabsContainer.getChildAt(currentPosition); TextView category_text = (TextView) currentTab.findViewById(R.id.category_text); float left = (float) (currentTab.getLeft() + category_text.getLeft()); float width = ((float) category_text.getWidth()) + left; if (currentPositionOffset > 0f && currentPosition < tabCount - 1) { ViewGroup nextTab = (ViewGroup)tabsContainer.getChildAt(currentPosition + 1); TextView next_category_text = (TextView) nextTab.findViewById(R.id.category_text); float next_left = (float) (nextTab.getLeft() + next_category_text.getLeft()); left = left * (1.0f - currentPositionOffset) + next_left * currentPositionOffset; width = width * (1.0f - currentPositionOffset) + currentPositionOffset * (((float) next_category_text.getWidth()) + next_left); } rect.set(((int) left) + getPaddingLeft(), getPaddingTop() + currentTab.getTop() + category_text.getTop(), ((int) width) + getPaddingLeft(), currentTab.getTop() + getPaddingTop() + category_text.getTop() + category_text.getHeight()); } // 計(jì)算滾動(dòng)范圍 private int getScrollRange() { return getChildCount() > 0 ? Math.max(0, getChildAt(0).getWidth() - getWidth() + getPaddingLeft() + getPaddingRight()) : 0; } // CategoryTabStrip與ViewPager聯(lián)動(dòng)邏輯 private void scrollToChild(int position, int offset) { if (tabCount == 0) { return; } calculateIndicatorRect(indicatorRect); int newScrollX = lastScrollX; if (indicatorRect.left < getScrollX() + scrollOffset) { newScrollX = indicatorRect.left - scrollOffset; } else if (indicatorRect.right > getScrollX() + getWidth() - scrollOffset) { newScrollX = indicatorRect.right - getWidth() + scrollOffset; } if (newScrollX != lastScrollX) { lastScrollX = newScrollX; scrollTo(newScrollX, 0); } } // 自定義繪圖 @Override public void draw(Canvas canvas) { super.draw(canvas); // 繪制高亮背景矩形紅框 calculateIndicatorRect(indicatorRect); if(indicator != null) { indicator.setBounds(indicatorRect); indicator.draw(canvas); } // 繪制背景紅框內(nèi)標(biāo)簽文本 int i = 0; while (i < tabsContainer.getChildCount()) { if (i < currentPosition - 1 || i > currentPosition + 1) { i++; } else { ViewGroup tab = (ViewGroup)tabsContainer.getChildAt(i); TextView category_text = (TextView) tab.findViewById(R.id.category_text); if (category_text != null) { TextDrawable textDrawable = drawables[i - currentPosition + 1]; int save = canvas.save(); calculateIndicatorRect(indicatorRect); canvas.clipRect(indicatorRect); textDrawable.setText(category_text.getText()); textDrawable.setTextSize(0, category_text.getTextSize()); textDrawable.setTextColor(getResources().getColor(R.color.category_tab_highlight_text)); int left = tab.getLeft() + category_text.getLeft() + (category_text.getWidth() - textDrawable.getIntrinsicWidth()) / 2 + getPaddingLeft(); int top = tab.getTop() + category_text.getTop() + (category_text.getHeight() - textDrawable.getIntrinsicHeight()) / 2 + getPaddingTop(); textDrawable.setBounds(left, top, textDrawable.getIntrinsicWidth() + left, textDrawable.getIntrinsicHeight() + top); textDrawable.draw(canvas); canvas.restoreToCount(save); } i++; } } // 繪制左右邊界陰影效果 i = canvas.save(); int top = getScrollX(); int height = getHeight(); int width = getWidth(); canvas.translate((float) top, 0.0f); if (left_edge == null || top <= 0) { if (right_edge == null || top >= getScrollRange()) { canvas.restoreToCount(i); } right_edge.setBounds(width - right_edge.getIntrinsicWidth(), 0, width, height); right_edge.draw(canvas); canvas.restoreToCount(i); } left_edge.setBounds(0, 0, left_edge.getIntrinsicWidth(), height); left_edge.draw(canvas); if (right_edge == null || top >= getScrollRange()) { canvas.restoreToCount(i); } right_edge.setBounds(width - right_edge.getIntrinsicWidth(), 0, width, height); right_edge.draw(canvas); canvas.restoreToCount(i); } private class PageListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { currentPosition = position; currentPositionOffset = positionOffset; scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); invalidate(); } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { if(pager.getCurrentItem() == 0) { // 滑動(dòng)到最左邊 scrollTo(0, 0); } else if (pager.getCurrentItem() == tabCount - 1) { // 滑動(dòng)到最右邊 scrollTo(getScrollRange(), 0); } else { scrollToChild(pager.getCurrentItem(), 0); } } } @Override public void onPageSelected(int position) { } } }
完整項(xiàng)目源代碼的資源下載 TouTiaoTabDemo.
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。