頂部滑動導航欄的實現
今日頭條頂部導航欄區域的主要部分是一個導航選單。導航選單是一組標籤的集合,在新聞客戶端中,每個標籤標示一個新聞類別,對應下面ViewPager控制元件的一個分頁面。當用戶在ViewPager區域滑動頁面時,對應的導航選單標籤也會相應的被選中,選中的標籤通過一個矩形紅框高亮顯示,紅框背景中的標籤文字變為白色,紅框外的區域標籤文字仍為灰色。當用戶直接在導航選單選中某個標籤時,ViewPager會自動的切換到對應的分頁面。在本文中導航選單作為一個單獨的UI控制元件實現,類名為CatagoryTabStrip,繼承自HorizontalScrollView,這樣就可以很容易的實現導航選單的左右滑動效果以及與下面ViewPager控制元件的聯動。
先看一下實現的效果對比:
頂部導航欄區域和ViewPager區域View層次結構
主介面佈局
在Activity中CatagoryTabStrip控制元件與ViewPager控制元件的聯合使用<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" style="@style/main_title_bar_style"> <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>
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控制元件的實現程式碼
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);
// 標籤容器
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);
// 繪製高亮區域作為滑動分頁指示器
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控制元件對應的ViewPager控制元件,實現聯動
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();
}
// 當附加在ViewPager介面卡上的資料發生變化時,應該呼叫該方法通知CategoryTabStrip重新整理資料
public void notifyDataSetChanged() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (int i = 0; i < tabCount; i++) {
addTab(i, pager.getAdapter().getPageTitle(i).toString());
}
}
// 新增一個標籤到導航選單
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);
}
// 計算滑動過程中矩形高亮區域的上下左右位置
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());
}
// 計算滾動範圍
private int getScrollRange() {
return getChildCount() > 0 ? Math.max(0, getChildAt(0).getWidth() - getWidth() + getPaddingLeft() + getPaddingRight()) : 0;
}
// CategoryTabStrip與ViewPager聯動邏輯
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);
}
// 繪製背景紅框內標籤文字
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) {
// 滑動到最左邊
scrollTo(0, 0);
} else if (pager.getCurrentItem() == tabCount - 1) {
// 滑動到最右邊
scrollTo(getScrollRange(), 0);
} else {
scrollToChild(pager.getCurrentItem(), 0);
}
}
}
@Override
public void onPageSelected(int position) {
}
}
}
相關推薦
頂部滑動導航欄的實現
隨著時間的推移現在的軟體要求顯示的內容越來越多,所以要在小的螢幕上能夠更好的顯示更多的內容,首先我們會想到底部選單欄,但是有時候像今日頭條新聞客戶端要顯示的內容太多,而且又想在主介面全部顯示出來,所以有加了頂部導航欄。 今日頭條頂部導航欄區域的主要部分是一個導航選單。導航選
FragmentTabHost實現底部導航欄和頂部滑動導航
一、實現底部導航欄效果《類似於RadioGroup》 ①MainActivity的xml佈局 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://sch
安卓頂部tab導航欄的實現
市面上許多APP都有頂部導航欄效果:下面我們自己來實現這個效果 首先我們先實現頂部導航條的佈局 頂部導航欄: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://sc
ios 導航欄透明, 上下滑動 導航欄 顏色漸變
滾動 pear action 文字 oid ati scom compact arm p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "PingFang SC"; color: #008400 } p.p2 { m
在UWP中頁面滑動導航欄置頂
效果圖 路由 .html bject 完成 我們 end 鼠標滾輪 istview 原文:在UWP中頁面滑動導航欄置頂最近在研究掌上英雄聯盟,主要是用來給自己看新聞,順便copy個界面改一下段位裝裝逼,可是在我copy的時候發現這個東西 當你滑動到一定距離的時候導航欄會置
mpvue實戰-手勢滑動導航欄
def 效果 設置 接下來 lin translate ini gif eba 寫點東西記錄一下美好時光,上周學習了一下通過mpuve開發微信小程序,看完文檔,就準備擼起袖子加油幹的時候,一開始就被支持手勢滑動的導航欄給搞懵逼了。求助一波百度和谷歌未果後,只能自己動腦動手
導航欄實現
批次 input ren fix isp -- 遮罩 position 刪除 導航欄實現之滾動條,本博客的滾動條的其中一部分細節就是這個 <style> .greyBox{position: fixed;top: 0;left: 0;width:
android4.4以上沉浸式狀態列和導航欄實現以及Bar的其他管理
自從android4.4開始,android手機狀態列再也不是一成黑的時代,之前叫做變色龍,miui6釋出會把他叫做沉浸式,之後大家就自然而然的接受了沉浸式這個名稱,其實實際應該叫做Translucent Bar,即為透明狀態列。 沉浸式實現原理其實是使整個activity佈局延伸到整個螢幕,然
Android 養成記-1--1.2 導航欄實現
先來幾張效果圖,看圖說話: 側邊欄 底部導航欄: 1 側邊導航欄實現 側邊導航欄主要是採用android 的佈局layout 來實現: 1) 在專案目錄下新建 wiget 目錄,新增NoSlideDrawerLayout.java
返回頂部 和 導航欄控制距離顯隱
返回頂部 <div class="g-cloent-right"> <ul> <li> <a href="#top" id="goToTop">
Android底部導航欄實現(二)之RadioGroup
這裡簡單記錄一下Android底部導航欄通過RadioGroup+Fragment的實現。 這裡寫圖片描述 佈局: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:and
還原淘寶首頁最頂部的導航欄(含下拉選單,圖示等)
還原了淘寶首頁最頂部的導航欄,包括了各個導航的下拉列表等(位置對齊稍微有些偏差,畢竟沒有原版設計圖),用到了jquery,js,CSS3等知識。沒有花時間去做錄屏GIF,就幾張效果圖看下:如下 原始導航欄進去後如上圖,當滑鼠劃過後下拉選單出現,本身的背景色改變等。如下: 上圖為區域選擇,每
iOS逆向之分析微信導航欄實現
最近需要實現微信的毛玻璃導航欄效果,嘗試了各種方式後還是有點差別,這在追求完美的設計師眼裡是絕不能忍的,於是只好“看看”原作是怎麼實現的。在逆向分析了微信的實現後,發現微信的實現十分特殊,文末會告訴大家答案:) 環境準備 一臺越獄裝置 OpenSSH 外掛 Cycript 外
Android沉浸式狀態列及導航欄實現
Android在4.4版本以後開始出現狀態列及導航欄透明化 實現程式碼如下 If (Build.Version.Sdk_Int >= Build.Version_Codes.Kitkat)
小程式頂部動態導航欄
<view style='width:{{nav_width}}%' bindtap='ActiveClick' wx:for="{{table}}" data-index='{{index}}' class="modle_1_nav_modle {{activeIndex==index?'modle
微信小程式入門四: 頂部、導航欄樣式、tabBar導航欄
例項內容導航欄樣式設定tabBar導航欄例項一:導航欄樣式設定小程式的導航欄樣式在app.json中定義。這裡設定導航,背景黑色,文字白色,文字內容測試小程式app.json內容:{ "pages":[ "pages/index/index", "page
樓層導航欄實現
//點選回到當前樓層aNav.click(function () { var t = aDiv.eq($(this).index()).offset().top; $('body,html').animate({ "scrollTop": t,
Fragment+Tablayout + BottomTabBar雙導航欄實現
https://mp.csdn.net/postedit 點選開啟連結.可以打賞一下或者加個關注 //底部導航 compile 'com.hjm:BottomTabBar:1.1.1' //tablayout implementatio
QT之導航欄實現
有道詞典大家一定用過,今天要分享的就是類似與有道詞典側邊導航欄的做法(PS:有道詞典 用的不是QT技術實現的 而是 Hex技術 點選檢視詳情) 上圖就是有道詞典的導航欄 開始正題,如何用QT
Android (爭取做到)最全的底部導航欄實現方法
本文(爭取做到)Android 最全的底部導航欄實現方法. 現在寫了4個主要方法. 還有一些個人感覺不完全切題的方法也會簡單介紹一下. 方法一. ViewPager + List<View> + PagerAdapter 先看a