1. 程式人生 > >Toolbar修改MenuItem字型顏色及佈局

Toolbar修改MenuItem字型顏色及佈局

一、style方式

<style name="ToolBarStyle" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="actionMenuTextColor">@android:color/white</item> <!--  敲定顏色-->
<item name="android:textSize">15sp</item> <!--  搞掂字型大小-->
<item name="android:textStyle"
>normal</item> </style>

<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:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize" app:colorControlNormal="@android:color/white" app:navigationIcon="@drawable/back" app:theme="@style/ToolBarStyle">

二、ActionProvider方式(方式1一般寫完之後全域性都變了,如果需要動態更換或者個別地方更改則可以使用該方式)

public class MainActionProvider extends ActionProvider {


    TextView tvTitle;
View.OnClickListener clickListener
; public MainActionProvider(Context context) { super(context); } @Override public View onCreateActionView() { Log.e("toolbar-menu", "onCreateActionView"); tvTitle = new TextView(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.MATCH_PARENT); tvTitle.setLayoutParams(params); tvTitle.setGravity(Gravity.CENTER); tvTitle.setPadding(DensityUtils.dp2px(getContext(),10),0,DensityUtils.dp2px(getContext(),10),0); tvTitle.setText(R.string.exit); tvTitle.setBackgroundResource(R.drawable.half_translucent_selector); tvTitle.setTextColor(BSSUtils.getColor(R.color.red_exit)); tvTitle.setOnClickListener(clickListener); return tvTitle;//或者自己寫的佈局inflate為View } @Override public void onPrepareSubMenu(SubMenu subMenu) { } @Override public boolean hasSubMenu() { return true; } public void setonClickListener(View.OnClickListener listener){ clickListener = listener; } public void setTvTitle(String title){ tvTitle.setText(title); } }

在Activity中新增如下程式碼

    @Override
public boolean onPrepareOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
mLogoutMenuItem = menu.findItem(R.id.logout);
mLogoutMenuItem.setVisible(false);
//        mLogoutMenuItem.getActionView();
MainActionProvider actionProvider = (MainActionProvider) MenuItemCompat.getActionProvider(mLogoutMenuItem);
actionProvider.setonClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                //點選事件}
        });
        return true;
}

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
}