<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_tool"
android:icon="@drawable/toolbar1"
app:showAsAction="ifRoom"
android:orderInCategory="50"
android:title="Tool">
</item>
<item
android:id="@+id/menu_finder"
android:icon="@drawable/toolbar2"
app:showAsAction="ifRoom"
android:orderInCategory="10"
android:title="Find">
</item>
</menu><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:contentInsetStart="0dp"
app:contentInsetLeft="0dp"
app:theme="@style/MyToolBarTheme"
app:titleTextAppearance="@style/Toolbar.TitleText"
>
<!--此处可以加你想要的View控件,如同LinearLayout类似的使用-->
</android.support.v7.widget.Toolbar>
<!--android:contentInsertStart contentInsetLeft是没有效果的不能保证控件靠近左边显示-->protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.mipmap.back);
//设置标题栏左边的图标样式,对应id为android.id.home ,用于返回上一级目录
setSupportActionBar(toolbar);
//将ToolBar对象设置为当前Activity的ActionBar
}@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_finder:
Toast.makeText(MainActivity.this,"touch finderItem",Toast.LENGTH_SHORT).show();
AndroidUtils.changeActivity(this,SearchActivity.class); //跳转到搜索页Activity
break;
case R.id.menu_tool:
Toast.makeText(MainActivity.this,"touch toolItem",Toast.LENGTH_SHORT).show();
AndroidUtils.showPopupMenu(this,toolbar,R.menu.popmenu,new OnPopupMenuItemClickListener(this)); //弹出共享菜单
break;
case android.R.id.home:
Toast.makeText(MainActivity.this,"touch up navigation",Toast.LENGTH_SHORT).show();
AndroidUtils.backToParent(this); //返回上一级目录
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
/**
* 弹出共享菜单
*/
public static void showPopupMenu(Context context,
View v,int menuResId, PopupMenu.OnMenuItemClickListener onMenuItemClickListener,
PopupMenu.OnDismissListener onDismissListener,int gravity){
PopupMenu popup = new PopupMenu(context, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(menuResId, popup.getMenu());
//利用反射显示图标
try {
Field field = popup.getClass().getDeclaredField("mPopup");
field.setAccessible(true);
MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popup);
mHelper.setForceShowIcon(true);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace(); }
popup.setOnMenuItemClickListener(onMenuItemClickListener);
if(onDismissListener!=null) popup.setOnDismissListener(onDismissListener);
popup.setGravity(gravity);
popup.show();
}
/**
* 跳转到父Activity
*/
public static void backToParent(Activity activity){
Intent upIntent = NavUtils.getParentActivityIntent(activity);
if(upIntent == null) {
activity.finish();
return;
}
if (NavUtils.shouldUpRecreateTask(activity, upIntent)) {
// This activity is NOT part of this app's task, so create a new task
// when navigating up, with a synthesized back stack.
TaskStackBuilder.create(activity)
// Add all of this activity's parents to the back stack
.addNextIntentWithParentStack(upIntent)
// Navigate up to the closest parent
.startActivities();
} else {
// This activity is part of this app's task, so simply
// navigate up to the logical parent activity.
NavUtils.navigateUpTo(activity, upIntent);
}
}@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
setHasOptionsMenu(true);
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar.
inflater.inflate(R.menu.my_menu, menu);
// ...
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.my_item:
// Handle this selection
return true;
default:
return super.onOptionsItemSelected(item);
}
}<declare-styleable name="Toolbar">
<attr format="reference" name="titleTextAppearance"/>
<attr format="reference" name="subtitleTextAppearance"/>
<attr name="title"/>
<attr name="subtitle"/>
<attr name="android:gravity"/>
<attr format="dimension" name="titleMargins"/>
<attr format="dimension" name="titleMarginStart"/>
<attr format="dimension" name="titleMarginEnd"/>
<attr format="dimension" name="titleMarginTop"/>
<attr format="dimension" name="titleMarginBottom"/>
<attr name="contentInsetStart"/>
<attr name="contentInsetEnd"/>
<attr name="contentInsetLeft"/>
<attr name="contentInsetRight"/>
<attr format="dimension" name="maxButtonHeight"/>
<attr format="reference" name="collapseIcon"/>
<attr format="string" name="collapseContentDescription"/>
<attr name="Theme"/> <!--这里可以修改ToolBar除了PopupMenu的所有信息(如背景色:注意java代码中的setBackgroundColor这个方法不要用存在bug!!!效果不好,使用这里的background属性进行设置) 设置的值可以参考主题ThemeOverlay.AppCompat.Dark.ActionBar-->
<attr name="popupTheme"/> <!--这里只能修改由ToolBar创建的弹出菜单,而对于自己通过创建PopupMenu对象显示的只能通过对context设置对应的主题进行设置,设置的值可以参考ThemeOverlay.AppCompat.Light-->
<attr format="reference" name="navigationIcon"/>
<attr format="string" name="navigationContentDescription"/>
<attr name="android:minHeight"/>
<attr name="logo"/>
<attr format="string" name="logoDescription"/>
<attr format="color" name="titleTextColor"/>
<attr format="color" name="subtitleTextColor"/>
</declare-styleable>public Toolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Need to use getContext() here so that we use the themed context
final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.Toolbar, defStyleAttr, 0);
mTitleTextAppearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0);
......//get操作
final CharSequence title = a.getText(R.styleable.Toolbar_title);
if (!TextUtils.isEmpty(title)) {
setTitle(title);
}
final CharSequence subtitle = a.getText(R.styleable.Toolbar_subtitle);
if (!TextUtils.isEmpty(subtitle)) {
setSubtitle(subtitle);
}
.....//set操作
}protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
int childState = 0;
.........//note1
final int measuredWidth = ViewCompat.resolveSizeAndState(
Math.max(width, getSuggestedMinimumWidth()),
widthMeasureSpec, childState & ViewCompat.MEASURED_STATE_MASK);
final int measuredHeight = ViewCompat.resolveSizeAndState(
Math.max(height, getSuggestedMinimumHeight()),
heightMeasureSpec, childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT);
setMeasuredDimension(measuredWidth, shouldCollapse() ? 0 : measuredHeight);
}protected void onLayout(boolean changed, int l, int t, int r, int b) {
final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
//Horizontal layout direction of this view is from Right to Left.
final int width = getWidth();
final int height = getHeight();
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int paddingBottom = getPaddingBottom();
int left = paddingLeft;
int right = width - paddingRight;
....
if (shouldLayout(mNavButtonView)) {....}
if (shouldLayout(mCollapseButtonView)) {....}
if (shouldLayout(mMenuView)) {....}
....
addCustomViewsWithGravity(mTempViews, Gravity.LEFT);
//ArrayList<View> mTempViews = new ArrayList<View>();
final int leftViewsCount = mTempViews.size();
for (int i = 0; i < leftViewsCount; i++) {
left = layoutChildLeft(mTempViews.get(i), left, collapsingMargins,
alignmentHeight);
}
addCustomViewsWithGravity(mTempViews, Gravity.RIGHT);{...... }
addCustomViewsWithGravity(mTempViews, Gravity.CENTER_HORIZONTAL);{...... }
mTempViews.clear();
}方法先对Toolbar中的导航栏、菜单栏、logo和标题等ActionBar中的属性进行布局。最后才给自己的childView进行布局。原文:http://blog.csdn.net/evan_man/article/details/51684947