Android使用Toolbar代替ActionBar

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

Android使用Toolbar代替ActionBar_第1张图片

默认styles配置主题


<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    
    
    
    <item name="colorAccent">@color/colorAccentitem>
style>

values-v19/styles.xml

<resources>
    
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        
        
        
        <item name="android:windowTranslucentStatus">trueitem>
        <item name="android:windowTranslucentNavigation">falseitem>
        <item name="colorAccent">@color/colorAccentitem>
    style>
resources>
values-v21/styles.xml

<resources>
    
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        
        
        
        
        
        <item name="android:windowTranslucentStatus">falseitem>
        <item name="android:windowTranslucentNavigation">falseitem>
        
        <item name="android:statusBarColor">@android:color/transparentitem>
        <item name="colorAccent">@color/colorAccentitem>
    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">
    
    
    <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"> 
        
            
            
            
        <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.注意底部导航栏问题

/**
 * 需要将 false 属性设置为 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.效果图如下

Android使用Toolbar代替ActionBar_第2张图片














你可能感兴趣的:(Android拓展)