项目来源: https://github.com/xuwj/ToolbarDemo#userconsent#

一、V7包升级问题

折腾好久,终于解决 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 的错误问题。。。

解决策略:翻墙,然后在sdkManager里面下载最新的support包,一定要是最新的。

然后引入到工程中来。

结构如下:

还有一点一定要注意,appcompat所需要的sdk也必须是最新的,不然不支持。最少21,刚刚我用19,里面的一些属性直接报错。切记。。。。

二、全局主题、样式

在application当中声明主题,表明是全局的概念,所有的activity都可以具有此属性。

Eclipse当中,在manifest中有版本控制,最小,目标版本等。

As当中,现在在build.gradle当中,如下图所示。而且,dependencies依赖于上面的compileSdkVersion buildToolsVersion (搭配相同)。

三、一些概念的理解

Widget 我们可以认为是一个部件。

PagerSlidingTabStrip :它是一个ViewPager 指示器,比ViewPageIndicator要好用的多,tab直接的过渡更加自然。

Toolbar是一种可定制的标题栏,actionbar比较死板,没多少人用。

Viewpager 和listview类似,一般我们将viewPager + fragmentPagerAdapter联合起来使用。

参考资料: Android中Styles、Themes、attrs介绍 http://www.open-open.com/lib/view/open1392260685837.html

Sytles 类似于css,把功能实现与外观分离开。Theme可由style来定义,放在application当中有全局的作用。

Attrs 是自定义参数,我们可以用它来对自定义属性进行定义。

一些控件假如不在xml中进行定义,我们就需要自己实例化,比如ImageButton tab = new ImageButton(getContext());

V7包的属性与android本身的属性不一样:

比如: android:colorPrimary ,这个是错误的,因为这个属性必须sdk21以上才支持,所以有了v7包。我们需要把android去掉才可以。

四、toolBarSytle无法找到解决方案

as出现这个问题,如何解决

错误竟然是我多定义了styles,原以为的适配用的,看来是理解错误。

必须是这样,我个人觉得同时有styles21 和 sytles 同时存在的时候,先适配sytles21,而我在sytles里面定义的东西在toolbar里面检索不到,所以出错。

所以解决方案:要么两个都定义,要么删掉一个。

五.Current min is xxxx ,call requires API xxx ?

所有这些问题都是因为兼容包的问题,因为我们默认导入的包都是低版本的包,但是随着版本的提高,我们需要适配的机型

比如说minSdk = 8,而上面需要的最小SDK版本是11.这个时候,我们必须引入v4包来解决问题。当然,有些高版本API可能还需要v7或者v13来做适配。

将刚刚的Fragmeng改为下面的 版本即可。

六、在fagment里面如何获取activity

必须要强转 MainActivity main = (MainActivity)getActivity(); //必须强转

最好是在onttach里面。

七、params 其实有多个,每一种布局里面有一套操作,都有相应的布局参数。Params

八、不同的IDE可能带来的问题:

解决方案:http://jingyan.baidu.com/article/7082dc1c77f979e40a89bddb.html

可能性:端口被占用

九、只有在toolbar上面设置的菜单才会有图标。

Toolbar说白了就是标题栏,导航栏一般用 PagerSlidingTabStrip (导航栏) + viewPage(类似listview的控件)做

覆盖与不覆盖的区别:

添加视图:

app:actionViewClass="android.support.v7.widget.SearchView"

menu菜单详解: http://www.open-open.com/lib/view/open1373981182669.html Android UI开发详解之ActionBar

其他资料: http://blog.csdn.net/lmj623565791/article/details/45303349 Android 5.x Theme 与 ToolBar 实战

http://blog.csdn.net/lmj623565791/article/details/42160391  Android 教你打造炫酷的ViewPagerIndicator 不仅仅是高仿MIUI

http://doc.okbase.net/HarryWeasley/archive/121430.html PagerSlidingTabStrip介绍及使用,让ViewPager更绚丽

程序代码:

参考资料: http://blog.csdn.net/codeeer/article/details/26447659 解决 Actionbar 溢出菜单不显示的问题

菜单溢出指的是 标题栏 右边的三点问题,有些手机不显示,按menu键才显示,这些都是实体键惹得祸,所以我们可以利用程序解决这个问题。

第一步:建立xml文件

Activity_main.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"> <include layout="@layout/tool_bar" /> <android.support.v4.widget.DrawerLayout
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"> <!-- 内容界面 --> <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <com.example.zhuxuekui.tool_bar.widget.PagerSlidingTabStrip
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:fillViewport="false">
</com.example.zhuxuekui.tool_bar.widget.PagerSlidingTabStrip> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"> <android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager> <EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout> </LinearLayout> <!-- 侧滑菜单内容 --> <LinearLayout
android:id="@+id/drawer_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/material_pink_A200"
android:orientation="vertical"
android:padding="8dp"> <TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout> </LinearLayout>

menu-main.xml

 <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" > <item
android:id="@+id/ab_search"
android:orderInCategory="80"
android:title="action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"/> <!--<item-->
<!--android:id="@+id/ab_search"-->
<!--android:orderInCategory="80"-->
<!--android:title="action_search"-->
<!--android:icon="@mipmap/ab_search"-->
<!--app:actionViewClass="android.support.v7.widget.SearchView"-->
<!--app:showAsAction="ifRoom|collapseActionView"/>--> <!--在toolbar上面设置才会有图标,且程序自动调用已经编辑好的程序-->
<item
android:id="@+id/action_share"
android:orderInCategory="90"
android:title="action_share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="action_settings"
app:showAsAction="never"/> </menu>

sytle.xml

 <?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. --> <!-- toolbar(actionbar)颜色 -->
<item name="colorPrimary">#4876FF</item>
<!-- 状态栏颜色 -->
<item name="colorPrimaryDark">#3A5FCD</item>
<!-- 窗口的背景颜色 -->
<item name="android:windowBackground">@android:color/white</item>
<!-- SearchView -->
<item name="searchViewStyle">@style/MySearchViewStyle</item>
<!-- 颜色强调,设置界面控件按钮的强调颜色 -->
<item name="colorAccent">@color/material_pink_A200</item> </style> <style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView">
<!--
Background for the search query section (e.g. EditText)
<item name="queryBackground">...</item>
Background for the actions section (e.g. voice, submit)
<item name="submitBackground">...</item>
Close button icon
<item name="closeIcon">...</item>
Search button icon
<item name="searchIcon">...</item>
Go/commit button icon
<item name="goIcon">...</item>
Voice search button icon
<item name="voiceIcon">...</item>
Commit icon shown in the query suggestion row
<item name="commitIcon">...</item>
Layout for query suggestion rows
<item name="suggestionRowLayout">...</item>
--> </style>
</resources>

第二步:

引入部件: PagerSlingTabStrip

 package com.example.zhuxuekui.tool_bar.widget;

 import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView; import com.example.zhuxuekui.tool_bar.R; import java.util.Locale; /**
* Created by zhuxuekui on 2015/6/3.
*/
public class PagerSlidingTabStrip extends HorizontalScrollView{ public interface IconTabProvider {
public int getPageIconResId(int position);
} // @formatter:off
private static final int[] ATTRS = new int[]{android.R.attr.textSize, android.R.attr.textColor};
// @formatter:on private LinearLayout.LayoutParams defaultTabLayoutParams;
private LinearLayout.LayoutParams expandedTabLayoutParams; private final PageListener pageListener = new PageListener();
public ViewPager.OnPageChangeListener delegatePageListener; private LinearLayout tabsContainer;
private ViewPager pager; private int tabCount; private int currentPosition = 0;
private int selectedPosition = 0;
private float currentPositionOffset = 0f; private Paint rectPaint;
private Paint dividerPaint; private int indicatorColor = 0xFF666666;
private int underlineColor = 0x1A000000;
private int dividerColor = 0x1A000000; private boolean shouldExpand = false;
private boolean textAllCaps = true; private int scrollOffset = 52;
private int indicatorHeight = 8;
private int underlineHeight = 2;
private int dividerPadding = 12;
private int tabPadding = 24;
private int dividerWidth = 1; private int tabTextSize = 12;
private int tabTextColor = 0xFF666666;
private int selectedTabTextColor = 0xFF666666;
private Typeface tabTypeface = null;
private int tabTypefaceStyle = Typeface.NORMAL; private int lastScrollX = 0; private int tabBackgroundResId = R.drawable.background_tab; private Locale locale; public PagerSlidingTabStrip(Context context) {
this(context, null);
} public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
this(context, attrs, 0);
} public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); 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);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm); // get system attrs (android:textSize and android:textColor) TypedArray a = context.obtainStyledAttributes(attrs, ATTRS); tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor); a.recycle(); // get custom attrs a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip); indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor);
underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor);
dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor);
indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight,
indicatorHeight);
underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight,
underlineHeight);
dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding,
dividerPadding);
tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight,
tabPadding);
tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground,
tabBackgroundResId);
shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand);
scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset,
scrollOffset);
textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps); a.recycle(); rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Paint.Style.FILL); dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth); defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); if (locale == null) {
locale = getResources().getConfiguration().locale;
}
} 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();
} public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
this.delegatePageListener = listener;
} public void notifyDataSetChanged() { tabsContainer.removeAllViews(); tabCount = pager.getAdapter().getCount(); for (int i = 0; i < tabCount; i++) { if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
} } updateTabStyles(); getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override
public void onGlobalLayout() {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
currentPosition = pager.getCurrentItem();
scrollToChild(currentPosition, 0);
}
}); } private void addTextTab(final int position, String title) { TextView tab = new TextView(getContext());
tab.setText(title);
tab.setGravity(Gravity.CENTER);
tab.setSingleLine();
addTab(position, tab);
} private void addIconTab(final int position, int resId) { ImageButton tab = new ImageButton(getContext());
tab.setImageResource(resId); addTab(position, tab); } private void addTab(final int position, View tab) {
tab.setFocusable(true);
tab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(position);
}
}); tab.setPadding(tabPadding, 0, tabPadding, 0);
tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams);
} private void updateTabStyles() { for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); if (v instanceof TextView) { TextView tab = (TextView) v;
tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
tab.setTypeface(tabTypeface, tabTypefaceStyle);
tab.setTextColor(tabTextColor); // setAllCaps() is only available from API 14, so the upper case
// is made manually if we are on a
// pre-ICS-build
if (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tab.setAllCaps(true);
} else {
tab.setText(tab.getText().toString().toUpperCase(locale));
}
}
if (i == selectedPosition) {
tab.setTextColor(selectedTabTextColor);
}
}
} } private void scrollToChild(int position, int offset) { if (tabCount == 0) {
return;
} int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset; if (position > 0 || offset > 0) {
newScrollX -= scrollOffset;
} if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
} } @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas); if (isInEditMode() || tabCount == 0) {
return;
} final int height = getHeight(); // draw underline
rectPaint.setColor(underlineColor);
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint); // draw indicator line
rectPaint.setColor(indicatorColor); // default: line below current tab
View currentTab = tabsContainer.getChildAt(currentPosition);
float lineLeft = currentTab.getLeft();
float lineRight = currentTab.getRight(); // if there is an offset, start interpolating left and right coordinates
// between current and next tab
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) { View nextTab = tabsContainer.getChildAt(currentPosition + 1);
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight(); lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
} canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint); // draw divider dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding,
dividerPaint);
}
} private class PageListener implements ViewPager.OnPageChangeListener { @Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset; scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); invalidate(); if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
} @Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
} if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
} @Override
public void onPageSelected(int position) {
selectedPosition = position;
updateTabStyles();
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
} } public void setIndicatorColor(int indicatorColor) {
this.indicatorColor = indicatorColor;
invalidate();
} public void setIndicatorColorResource(int resId) {
this.indicatorColor = getResources().getColor(resId);
invalidate();
} public int getIndicatorColor() {
return this.indicatorColor;
} public void setIndicatorHeight(int indicatorLineHeightPx) {
this.indicatorHeight = indicatorLineHeightPx;
invalidate();
} public int getIndicatorHeight() {
return indicatorHeight;
} public void setUnderlineColor(int underlineColor) {
this.underlineColor = underlineColor;
invalidate();
} public void setUnderlineColorResource(int resId) {
this.underlineColor = getResources().getColor(resId);
invalidate();
} public int getUnderlineColor() {
return underlineColor;
} public void setDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
invalidate();
} public void setDividerColorResource(int resId) {
this.dividerColor = getResources().getColor(resId);
invalidate();
} public int getDividerColor() {
return dividerColor;
} public void setUnderlineHeight(int underlineHeightPx) {
this.underlineHeight = underlineHeightPx;
invalidate();
} public int getUnderlineHeight() {
return underlineHeight;
} public void setDividerPadding(int dividerPaddingPx) {
this.dividerPadding = dividerPaddingPx;
invalidate();
} public int getDividerPadding() {
return dividerPadding;
} public void setScrollOffset(int scrollOffsetPx) {
this.scrollOffset = scrollOffsetPx;
invalidate();
} public int getScrollOffset() {
return scrollOffset;
} public void setShouldExpand(boolean shouldExpand) {
this.shouldExpand = shouldExpand;
notifyDataSetChanged();
} public boolean getShouldExpand() {
return shouldExpand;
} public boolean isTextAllCaps() {
return textAllCaps;
} public void setAllCaps(boolean textAllCaps) {
this.textAllCaps = textAllCaps;
} public void setTextSize(int textSizePx) {
this.tabTextSize = textSizePx;
updateTabStyles();
} public int getTextSize() {
return tabTextSize;
} public void setTextColor(int textColor) {
this.tabTextColor = textColor;
updateTabStyles();
} public void setTextColorResource(int resId) {
this.tabTextColor = getResources().getColor(resId);
updateTabStyles();
} public int getTextColor() {
return tabTextColor;
} public void setSelectedTextColor(int textColor) {
this.selectedTabTextColor = textColor;
updateTabStyles();
} public void setSelectedTextColorResource(int resId) {
this.selectedTabTextColor = getResources().getColor(resId);
updateTabStyles();
} public int getSelectedTextColor() {
return selectedTabTextColor;
} public void setTypeface(Typeface typeface, int style) {
this.tabTypeface = typeface;
this.tabTypefaceStyle = style;
updateTabStyles();
} public void setTabBackground(int resId) {
this.tabBackgroundResId = resId;
updateTabStyles();
} public int getTabBackground() {
return tabBackgroundResId;
} public void setTabPaddingLeftRight(int paddingPx) {
this.tabPadding = paddingPx;
updateTabStyles();
} public int getTabPaddingLeftRight() {
return tabPadding;
} @Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
currentPosition = savedState.currentPosition;
requestLayout();
} @Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPosition = currentPosition;
return savedState;
} static class SavedState extends BaseSavedState {
int currentPosition; public SavedState(Parcelable superState) {
super(superState);
} private SavedState(Parcel in) {
super(in);
currentPosition = in.readInt();
} @Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPosition);
} public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
} @Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}

定义基类 BaseCardFragment:

 package com.example.zhuxuekui.tool_bar;

 import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView; /**
* Created by zhuxuekui on 2015/6/3.
*/ //每次都会new出一个fragment,这是一个基类
public class BaseCardFragment extends Fragment{ private static final String ARG_POSITION = "position"; private int position;
private static final int[] drawables = {R.mipmap.frag1, R.mipmap.frag2, R.mipmap.frag3, R.mipmap.frag4,
R.mipmap.f, R.mipmap.fo, R.mipmap.s}; public static BaseCardFragment newInstance(int position) {
BaseCardFragment f = new BaseCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
fl.setBackgroundResource(drawables[position]);
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
.getDisplayMetrics()); TextView v = new TextView(getActivity());
params.setMargins(margin, margin, margin, margin);
v.setLayoutParams(params);
v.setLayoutParams(params);
v.setGravity(Gravity.BOTTOM);
v.setText("fragment " + (position + 1)); fl.addView(v);
return fl;
} /**
* 提供当前Fragment的主色调的Bitmap对象,供Palette解析颜色
*
* @return
*/
public static int getBackgroundBitmapPosition(int selectViewPagerItem) {
return drawables[selectViewPagerItem];
}
}

定义主类:

 package com.xwj.toolbardemo;

 import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.Toast; import com.xwj.toolbardemo.widget.PagerSlidingTabStrip; import java.lang.reflect.Field; /**
* 此Demo 用到的控件:
* ToolBar + Drawer
* PagerSlidingTabStrip + Palette(调色板)
* 实现抽屉与变色效果
*/ public class MainActivity extends ActionBarActivity { //抽屉效果 侧边栏
private DrawerLayout mDrawerLayout;
//actionbar和抽屉的链接效果,触发控件
private ActionBarDrawerToggle mDrawerToggle;
//标题栏分享图标
private ShareActionProvider mShareActionProvider;
//菜单栏控件
private PagerSlidingTabStrip mPagerSlidingTabStrip;
//整个内容控件结合fragment一起使用
private ViewPager mViewPager;
//标题栏
private Toolbar mToolbar; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* DrawerLayout不覆盖Toolbar
*/
setContentView(R.layout.activity_main);
/**
* DrawerLayout覆盖Toolbar
*/
//setContentView(R.layout.activity_main_toggleover); //初始化控件
initViews();
//处理溢出菜单问题 就是右侧三点问题
setOverflowShowingAlways();
} private void initViews() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
// toolbar.setLogo(R.drawable.ic_launcher);
// 标题的文字需在setSupportActionBar之前,不然会无效
mToolbar.setTitle("ToolbarDemo");
// toolbar.setSubtitle("副标题");
setSupportActionBar(mToolbar);//标题栏
/* 上面的这些通过ActionBar来设置也是一样的,注意要在setSupportActionBar(toolbar);之后,不然就报错了 */
// getSupportActionBar().setTitle("标题");
// getSupportActionBar().setSubtitle("副标题");
// getSupportActionBar().setLogo(R.drawable.ic_launcher); //我们可以在Menu方法和onOptionsItemSelected中设置监听,下面实现和最底下的效果一致
/* 菜单的监听可以在toolbar里设置,也可以像ActionBar那样,通过下面的两个回调方法来处理 */
// mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
// @Override
// public boolean onMenuItemClick(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Toast.makeText(MainActivity.this, "action_settings", Toast.LENGTH_SHORT).show();
// break;
// case R.id.action_share:
// Toast.makeText(MainActivity.this, "action_share", Toast.LENGTH_SHORT).show();
// break;
// default:
// break;
// }
// return true;
// }
// });
// mToolbar.setOnCreateContextMenuListener(this);
getSupportActionBar().setHomeButtonEnabled(true); // 设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* findView */
//抽屉布局,其实和toobar相关的,他们是嵌套的关系。
//actionbar的切换效果 toggle 触发的意思
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open,
R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//当drawer页面打开的时候,京东的那个RunningMan动画就是在此时关闭和打开的
Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_SHORT).show();
} @Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
//当drawer页面关闭的时候
Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_SHORT).show();
} };
//同步
mDrawerToggle.syncState();
//将DrawerLayout与DrawerToggle建立联系
mDrawerLayout.setDrawerListener(mDrawerToggle); //下面是ViewPager + mPagerSlidingTabStrip 部分
mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
//建立两者关系
mPagerSlidingTabStrip.setViewPager(mViewPager);
mPagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override
public void onPageSelected(int arg0) {
colorChange(arg0);
} @Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
} @Override
public void onPageScrollStateChanged(int arg0) {
}
});
//设置默认配置
initTabsValue();
} /**
* mPagerSlidingTabStrip默认值配置
*/
private void initTabsValue() {
// 底部游标颜色
mPagerSlidingTabStrip.setIndicatorColor(Color.BLUE);
// tab的分割线颜色
mPagerSlidingTabStrip.setDividerColor(Color.TRANSPARENT);
// tab背景
mPagerSlidingTabStrip.setBackgroundColor(Color.parseColor("#4876FF"));
// tab底线高度
mPagerSlidingTabStrip.setUnderlineHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
1, getResources().getDisplayMetrics()));
// 游标高度
mPagerSlidingTabStrip.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
5, getResources().getDisplayMetrics()));
// 选中的文字颜色
mPagerSlidingTabStrip.setSelectedTextColor(Color.WHITE);
// 正常文字颜色
mPagerSlidingTabStrip.setTextColor(Color.BLACK);
} /**
* 界面颜色的更改
*/
@SuppressLint("NewApi")
private void colorChange(int position) {
// 用来提取颜色的Bitmap
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
BaseCardFragment.getBackgroundBitmapPosition(position));
// Palette的部分
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
/**
* 提取完之后的回调方法
*/
@Override
public void onGenerated(Palette palette) {
if (palette != null) {
Palette.Swatch vibrant = palette.getVibrantSwatch();
/* 界面颜色UI统一性处理,看起来更Material一些 */
mPagerSlidingTabStrip.setBackgroundColor(vibrant.getRgb());
mPagerSlidingTabStrip.setTextColor(vibrant.getTitleTextColor());
// 其中状态栏、游标、底部导航栏的颜色需要加深一下,也可以不加,具体情况在代码之后说明
mPagerSlidingTabStrip.setIndicatorColor(colorBurn(vibrant.getRgb())); mToolbar.setBackgroundColor(vibrant.getRgb());
if (android.os.Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
// API>=21以上才能实现此效果,当然也可以用开源的状态栏SystemBarTintManager实现(支持4.4以上)
window.setStatusBarColor(colorBurn(vibrant.getRgb()));//颜色加深
window.setNavigationBarColor(colorBurn(vibrant.getRgb()));
}
// 释放掉,避免卡顿
bitmap.recycle();
} }
}); } /**
* 颜色加深处理
*
* @param RGBValues RGB的值,由alpha(透明度)、red(红)、green(绿)、blue(蓝)构成,
* Android中我们一般使用它的16进制,
* 例如:"#FFAABBCC",最左边到最右每两个字母就是代表alpha(透明度)、
* red(红)、green(绿)、blue(蓝)。每种颜色值占一个字节(8位),值域0~255
* 所以下面使用移位的方法可以得到每种颜色的值,然后每种颜色值减小一下,在合成RGB颜色,颜色就会看起来深一些了
* @return
*/
private int colorBurn(int RGBValues) {
Log.e("-----",RGBValues+"");
int alpha = RGBValues >> 24; int red = RGBValues >> 16 & 0xFF;
Log.e("--red---",red+""); int green = RGBValues >> 8 & 0xFF;
Log.e("--green---",green+""); int blue = RGBValues & 0xFF;
Log.e("--blue---",blue+"");
red = (int) Math.floor(red * (1 - 0.1));
green = (int) Math.floor(green * (1 - 0.1));
blue = (int) Math.floor(blue * (1 - 0.1));
return Color.rgb(red, green, blue);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menu
.findItem(R.id.action_share));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/*");
mShareActionProvider.setShareIntent(intent); MenuItem searchItem = menu.findItem(R.id.ab_search); //为menu事件设置监听
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(MainActivity.this, "打开", Toast.LENGTH_SHORT).show();
return true;
} @Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
}); return super.onCreateOptionsMenu(menu);
} //为toolbar上面的每一个mune设置事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(MainActivity.this, "action_settings", Toast.LENGTH_SHORT).show();
break;
case R.id.action_share:
Toast.makeText(MainActivity.this, "action_share", Toast.LENGTH_SHORT).show();
break;
case R.id.ab_search:
Toast.makeText(MainActivity.this, "ab_search", Toast.LENGTH_SHORT).show();
break;
default:
break;
} return super.onOptionsItemSelected(item);
} /**
* 处理溢出菜单问题
*/
private void setOverflowShowingAlways() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
} catch (Exception e) {
e.printStackTrace();
}
} //每次点一下Viewpager就会新建一个fragment, 把pagerAdpater 想象成 arrayAdapter。
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"推荐", "分类", "本月热榜", "热门推荐", "专栏", "热门收藏", "随缘"}; public MyPagerAdapter(FragmentManager fm) {
super(fm);
} @Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
} @Override
public Fragment getItem(int position) {
return BaseCardFragment.newInstance(position);
} @Override
public int getCount() {
return TITLES.length;
}
}
}

Toolbar的使用的更多相关文章

  1. 安卓自定义组合控件--toolbar

    最近在学习安卓APP的开发,用到了toolbar这个控件, 最开始使用时include layout这种方法,不过感觉封装性不好,就又改成了自定义组合控件的方式. 使用的工具为android stud ...

  2. Android开发之Android Material Design Toolbar自定义随笔

    一.自定义Toolbar的menu: 在menu下新建menu.xml文件,自定义menu的样式: <menu xmlns:android="http://schemas.androi ...

  3. Android Toolbar 开发总结

    初识 Toolbar Toolbar是在 Android 5.0 开始推出的一个 Material Design 风格的导航控件 ,Google 非常推荐大家使用 Toolbar 来作为Android ...

  4. 安卓Design包之AppBar和Toolbar的联用

    前面讲了Design包的的CoordinatorLayout和SnackBar的混用,现在继续理解Design包的AppBar; AppBarLayout跟它的名字一样,把容器类的组件全部作为AppB ...

  5. 分别用ToolBar和自定义导航栏实现沉浸式状态栏

    一.ToolBar 1.在build.gradle中添加依赖,例如: compile 'com.android.support:appcompat-v7:23.4.0' 2.去掉应用的ActionBa ...

  6. 【Windows编程】系列第六篇:创建Toolbar与Statusbar

    上一篇我们学习了解了如何使用Windows GDI画图,该应用程序都是光光的静态窗口,我们使用Windows应用程序,但凡稍微复杂一点的程序都会有工具栏和状态栏,工具栏主要用于一些快捷功能按钮.比如典 ...

  7. Ext动态加载Toolbar

    在使用Ext的GridPanel时候,有时候需要面板不用重新加载而去更新Store或者Toolbar,Store的方法有很多,例如官方api给我们提供的Store.load(),Store.reLoa ...

  8. 浅谈ListView滑动隐藏显示ToolBar

    引言 在App日益追求体验的时代,优秀的用户体验往往会使产品脱颖而出.今天我们就来介绍一种简单的滑动ListView来显示或者隐藏ToolBar的功能. 布局文件 下面我们来看一下这个主界面的布局文件 ...

  9. Android 自定义ToolBar详细使用

    自定义xml设置ToolBar,通过menu文件扩展选项,通过继承baseactivity使用 1.ToolBar布局 <?xml version="1.0" encodin ...

  10. ExtJS扩展:扩展grid之toolbar button禁用表达式

          在前一篇文章我们扩展了grid通过选中记录数来禁用toolbar上的按钮,有时候我们需要通过记录中的数据来决定是否禁用按钮,今天我们就来扩展它.       照例,最新的代码和例子都在gi ...

随机推荐

  1. App开发流程之数据持久化和编译静态链接库

    先记录数据持久化. iOS客户端提供的常用数据持久化方案:NSUserDefaults代表的用户设置,NSKeydArchiver代表的归档,plist文件存储,SQLite数据库(包括上层使用的Co ...

  2. 【读书笔记】iOS-NSString的length

    NSString的length方法能够准确无误地处理国际字符串,如含有俄文,中文或者日本文字符的字符串,以及使用Unicode国际字符标准的字符串.在C语言中处理这些国际字符串是件令人非常头疼的事情 ...

  3. IOS组件绑定无效错误

    报错的原因:界面按钮事件没有绑定到源代码或者相关的代码被注释了.比如你的button组件以及绑定到IBOutlet,但是viewcontrol.m上没有相关的代码,就会出现异常.

  4. win7 64位安装oracle10g出现未知错误,程序异常终止解决方法

    修改Oracle 10G\database\stage\prereq\db\refhost.xml 在 </SYSTEM> <CERTIFIED_SYSTEMS>后面添加 &l ...

  5. 教你怎样写自定义IP地址算法

    通过IP地址可以看到算法规律,写成自定义IP地址,也可以把IP地址转为自定格式的IP地址.也可以用于加密一些明文数字.起始次方可自定义(以1次方和0次方为例) a.以下写正反算法(以1次方为最小单位) ...

  6. java微信接口之四—上传素材

    一.微信上传素材接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=A ...

  7. PHP实战-文章发布系统学习记录

    跟随大师的步伐,一步一步向前行进,PHP学习之路中的历程. 如果图片不能正常查看请访问云笔记链接 http://note.youdao.com/share/?id=3c25d8c03ef946d9c6 ...

  8. cordova Process finished with exit code -1

    安装完cordova之后,创建一个测试项目后,运行报Process finished with exit code -1,经过查找原因,是因为gradle没有安装,在http://www.androi ...

  9. 《JavaScript修炼之道》读书笔记

    1.参考书目 入门:<JavaScript DOM编程艺术>第二版 进阶:<JavaScript高级程序设计>第二版.<JavaScript编程精粹> <Ja ...

  10. jdk环境搭建

    win7+jdk环境变量配置 进行java开发,首先要安装jdk,安装了jdk后还要进行环境变量配置:1.下载jdk(http://java.sun.com/javase/downloads/inde ...