android Toolbar 使用

1、导航控制器:
   google 为了统一导航 android3.0 出来了 ActionBar, ActionBar使用比较费劲
   JakeWharton
ActionBarSherlock   很多人都用这个
后来 android 推出了 android.support.v7.widget.Toolbar

  ToolBar功能:  管理标题、返回按钮、菜单

2. 使用toolbar

2.1 添加依赖

 compile 'com.android.support:design:27.1.1'

2.2. 布局 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mk.denganzhi.com.cehua.MainActivity"
    android:orientation="vertical">

    <!-- 定义toolbar控件,navigationIcon 定义返回按键 -->
    <android.support.v7.widget.Toolbar
        android:id="@+id/mytoolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="网易新闻"
        app:subtitle="新闻"
        android:background="?attr/colorPrimary"
        app:logo="@mipmap/ic_launcher"
        app:navigationIcon="@mipmap/add_pwd_left"
        >


    </android.support.v7.widget.Toolbar>
    
</LinearLayout>

2.3. 设置主题 

  <!-- 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="colorAccent">@color/colorAccent</item>
    </style>

2.4.  把toolbar添加到Activity中 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ///使用Toolbar代码ActionBar
        Toolbar toolbar= findViewById(R.id.mytoolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

效果图:

发布了97 篇原创文章 · 获赞 100 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/dreams_deng/article/details/104970554