Material Design控件-toolbar

来源:互联网 发布:淘宝上那能买到正品mlb 编辑:程序博客网 时间:2024/05/21 04:42


1.ToolBar

使用原因:ActionBar 固定在上面,扩展性不好,Google使用Toolbar来代替Actionbar

使用方法:

     一。去除ActionBar,我们之前带有ActionBar是因为使用了带ActionBar的主题,所以我们得换换主题,

在AndroidManifest.xml中 找到android:theme,

ctrl +鼠标左键点击@style/AppTheme,

我们将@style/AppTheme依赖的的样式改为Theme.AppCompat.Light.NoActionBar

AndroidManifest.xml:

<application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>
styles.xml:

    <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>


二。加入toolbar 步骤一:在布局文件中加入toolbar

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"><android.support.v7.widget.Toolbar    android:id="@+id/toolbar"    android:layout_width="match_parent"    android:layout_height="?attr/colorPrimary"    android:background="?attr/colorPrimary">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:textSize="20sp"        android:text="@string/app_name"/>    </android.support.v7.widget.Toolbar></RelativeLayout>
这里加入Textview是为了让标题居中显示,否则标题会显示在左边


步骤二:加入代码

   private void initView() {        toolbar = (Toolbar)findViewById(R.id.toolbar);        setSupportActionBar(toolbar);   //设置使用toolbar        setTitle(null);   //设置原标题为空,这是个显示在左边的标题    }

这样就完成了。

我们看上面的动图右边还有一个menu按键,怎么加入呢?

步骤一:在menu文件夹下加入toolbar.xml文件,内容如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">    <item android:id="@+id/download"        android:icon="@drawable/listen"        android:title="下载"        app:showAsAction="always"/></menu>

步骤二:加入代码

//加载该menu文件

    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.toolbar,menu);        return true;    }

//设置点击menu按键时的行为,这里我们是提示You click download
    @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId()){            case R.id.download:                Toast.makeText(this,"You click download",Toast.LENGTH_SHORT).show();                break;            default:                break;        }        return true;    }




        


0 0
原创粉丝点击