Android使用Toolbar代替ActionBar

1.通常需要配置三个styles.xml


默认styles配置主题

<!-- Base application theme. 隐藏掉ActionBar即可--> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <!-- Customize your theme here. -->  <!--<item name="colorPrimary">@color/colorPrimary</item>-->  <!--<item name="colorPrimaryDark">@color/colorPrimaryDark</item>-->  <item name="colorAccent">@color/colorAccent</item>
</style>

values-v19/styles.xml

<resources>
    <!-- Base application theme. -->  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->  <!--<item name="colorPrimary">@color/colorPrimary</item>-->  <!--<item name="colorPrimaryDark">@color/colorPrimaryDark</item>-->  <item name="android:windowTranslucentStatus">true</item><!--状态栏透明-->
        <item name="android:windowTranslucentNavigation">false</item><!--导航栏不透明,否则底部会导致内容被覆盖-->
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>
values-v21/styles.xml

<resources>
    <!-- Base application theme. -->  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->  <!--<item name="colorPrimary">@color/colorPrimary</item>-->  <!--<item name="colorPrimaryDark">@color/colorPrimaryDark</item>-->  <!--<item name="android:windowTranslucentStatus">true</item>-->  <!--<item name="android:windowTranslucentNavigation">true</item>-->  <item name="android:windowTranslucentStatus">false</item><!--这个值设置false,statusBarColor状态栏透明-->         <item name="android:windowTranslucentNavigation">false</item><!--导航栏不透明,否则底部会导致内容被覆盖-->
        <!--Android 5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色-->  <item name="android:statusBarColor">@android:color/transparent</item><!--状态栏透明-->
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

2.自定义一个ToolBar的layout/view_toolbar.xml

<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:app="http://schemas.android.com/apk/res-auto"  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  android:id="@+id/app_bar_layout"  android:layout_width="match_parent"  android:layout_height="wrap_content"  app:elevation="3dp">
    <!--app:navigationIcon="@drawable/navigationicon"-->  <!--android:navigationIcon="@drawable/navigationicon"-->  <android.support.v7.widget.Toolbar  android:id="@+id/toolbar"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:background="@drawable/home_top_bg"  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  app:popupTheme="@style/ThemeOverlay.AppCompat.Light"  app:logo="@drawable/home_logo"   app:layout_scrollFlags="scroll|enterAlways"> <!--android:fitsSystemWindows="true"-->  <!--<ImageView-->  <!--android:layout_width="wrap_content"-->  <!--android:layout_height="wrap_content"-->  <!--android:background="@drawable/home_logo"/>-->  <RelativeLayout  android:layout_width="match_parent"  android:layout_height="wrap_content">
            <TextView  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_alignParentRight="true"  android:textSize="@dimen/middle_size"  android:textColor="@color/white"  android:id="@+id/delay"/>
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

3.引用Toolbar布局

<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"  style="@style/all_match_parent"  android:orientation="vertical">
    <ImageView  style="@style/all_match_parent"  android:background="@drawable/qr_authorization_bg"/>
    <LinearLayout  style="@style/all_match_parent"  android:orientation="vertical">
        <include layout="@layout/view_toolbar"/>
    </LinearLayout>
</FrameLayout>

4.自定义Activity的基类ToolBarActivity

/**  * Toolbar基类  */  public abstract class ToolbarActivity extends AppCompatActivity { 
    abstract protected int provideContentViewId();

    public void onToolbarClick() {}

    protected AppBarLayout mAppBar;
    protected Toolbar mToolbar;
    protected TextView delay;
    protected boolean mIsHidden = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(provideContentViewId());
        mAppBar = (AppBarLayout)findViewById(R.id.app_bar_layout);
        mToolbar = (Toolbar)findViewById(R.id.toolbar);
        delay = (TextView)findViewById(R.id.delay);
        delay.setVisibility(View.GONE);
        if(mToolbar == null && mAppBar == null){
            throw new IllegalStateException(
                    "The subclass of ToolbarActivity must contain a toolbar.");
        }
        mToolbar.setOnClickListener(v -> onToolbarClick());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
//设置大于等于Build.VERSION_CODES.KITKAT版本,则Toolbar占据状态栏的空间
 {
            mToolbar.getLayoutParams().height = getAppBarHeight();
            mToolbar.setPadding(mToolbar.getPaddingLeft(),
                    getStatusBarHeight(),
                    mToolbar.getPaddingRight(),
                    mToolbar.getPaddingBottom());
 }
        //设置标题为空  mToolbar.setTitle("");
// // App Logo // mToolbar.setLogo(R.mipmap.ic_launcher_round);  setSupportActionBar(mToolbar);
// Navigation Icon 要設定在 setSupoortActionBar 才有作用 // 否則會出現 back button // mToolbar.setNavigationIcon(R.mipmap.ic_launcher_round);  if(canBack()){
            ActionBar actionBar = getSupportActionBar();
            if(actionBar != null){
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        if(Build.VERSION.SDK_INT>=21){
            mAppBar.setElevation(10.6f);
        }
    }

    private int getAppBarHeight()
    {
        return dip2px(56)+getStatusBarHeight();
    }

    private int getStatusBarHeight()
    {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");

        if (resourceId > 0)
        {
            result = getResources().getDimensionPixelSize(resourceId);
        }

        return result;
    }

    private int dip2px(float dipValue)
    {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public boolean canBack(){
        return false;
    }

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    protected void setAppBarAlpha(float alpha) {
        mAppBar.setAlpha(alpha);
    }

    protected void hideOrShowToolbar(){
        mAppBar.animate()
                .translationY(mIsHidden ? 0 : -mAppBar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsHidden = !mIsHidden;
    }
}

5.继承ToolBarActivity类就可以正常显示ToolBar了

public class AccountListActivity extends ToolbarActivity{
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_account_list;
    }


    @Override
    public boolean canBack() {
        return true;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

6.注意底部导航栏问题

/**  * 需要将 <item name="android:windowTranslucentNavigation">false</item> 属性设置为 false ,是 Navigation Bar 不透明,但效果却并没有变成我们想象的那样,Status Bar 的样式完全失效。  事实上,android:windowTranslucentNavigation 这个属性额外设置了 SYSTEM_UI_FLAG_LAYOUT_STABLE 和 SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 两个 flag。所以我们需要再绘制完 Status Bar 以后重新请求这两个 flag 。  在 onCrate 方法中调用  getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 在ToolBarActivity的onCreate方法中加入下面这句话就可以了  */ getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

7.效果图如下