Android ToolBar的使用
生活随笔
收集整理的這篇文章主要介紹了
Android ToolBar的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載請標明出處:http://blog.csdn.net/zhaoyanjun6/article/details/64130211
本文出自【趙彥軍的博客】
前言
ToolBar的出現是為了替換之前的ActionBar的各種不靈活使用方式,相反,ToolBar的使用變得非常靈活,因為它可以讓我們自由往里面添加子控件.低版本要使用的話,可以添加support-v7包.
要使用ToolBar,首先引入v7包
compile 'com.android.support:appcompat-v7:25.3.0'還需要在使用 ToolBar 的 Activity 下面添加去掉 ActionBar 的主題 :
android:theme="@style/Theme.AppCompat.Light.NoActionBar"比如:
<activity android:name=".MainActivity"android:theme="@style/Theme.AppCompat.Light.NoActionBar"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter> </activity>如果沒有添加去掉 ActionBar 的主題 , 會報異常:
ToolBar 的使用
創建 activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#FFFFFF"><!-- android:layout_height="?attr/actionBarSize" 根據手機分辨率自動分配高度--><android.support.v7.widget.Toolbar android:id="@+id/toolbar"android:layout_width="match_parent"android:background="@color/colorAccent"android:layout_height="?attr/actionBarSize"><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content"><TextView android:id="@+id/tv1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="個人中心"android:layout_centerInParent="true"android:textColor="#ffffff"android:textSize="20sp"/><ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@mipmap/ic_launcher"android:layout_alignParentRight="true"/></RelativeLayout></android.support.v7.widget.Toolbar></RelativeLayout>MainActivity 的代碼邏輯
package com.constraintlayout.app; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Toast;public class MainActivity extends AppCompatActivity {private Toolbar mToolbar ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mToolbar = (Toolbar) findViewById(R.id.toolbar);mToolbar.setTitleTextColor(Color.YELLOW);//取代原本的actionbarsetSupportActionBar(mToolbar);//ToolBar里面還可以包含子控件mToolbar.findViewById(R.id.tv1 ).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(MainActivity.this, "點擊自定義按鈕", Toast.LENGTH_SHORT).show();}});} }效果圖:
總結
以上是生活随笔為你收集整理的Android ToolBar的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 借助Stetho在Chr
- 下一篇: Android 混淆详解