前面一篇已经简单地介绍了Toolbar及沉浸式状态栏的实现方式,这篇作为对前面的一些补充,希望能够帮助到你
文字介绍不多,主要内容在注释里写明了,仔细阅读代码应该能很好地理解。
使用Toolbar需要依赖appcompat-v7
- 使用Android Studio的童鞋请在app module的build.gradle中添加
dependencies {
compile 'com.android.support:appcompat-v7:24.1.1'
}
版本号酌情选择即可
- 使用Eclipse的童鞋请先添加appcompat-v7作为你的项目的library,不清楚的请百度、Google。
隐藏Actionbar
为了方便去除Actionbar,这里采用自定义theme
继承自"Theme.AppCompat.Light.NoActionBar"的方式,以下罗列了需要用到的style。
styles.xml
<!--Custom base application theme-->
<style name="CAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!--Toolbar 导航按钮(返回按钮)样式-->
<item name="toolbarNavigationButtonStyle">@style/mToolbarNavigationButtonStyle</item>
</style>
<!--Toolbar Navigation Button Sytle-->
<style name="mToolbarNavigationButtonStyle" parent="@style/Widget.AppCompat.Toolbar.Button.Navigation">
<item name="android:minWidth">40dp</item>
<item name="android:padding">0dp</item>
<item name="android:scaleType">centerInside</item>
</style>
<!--Custom Toolbar Style -->
<style name="mToolbarStyle" parent="@style/Widget.AppCompat.Toolbar">
<!-- 设置该属性解决Toolbar左边空白 默认为16dp-->
<item name="contentInsetStart">0dp</item>
<item name="contentInsetStartWithNavigation">0dp</item>
<item name="titleMargin">0dp</item>
<!--Toolbar Button min Height.Suggest use 0dp,
also can use your Toolbar's Height-->
<item name="android:minHeight">0dp</item>
<!--Toolbar Button Max height.
Suggest use size <= your custom Toolbar's Height-->
<item name="maxButtonHeight">100dp</item>
</style>
<!--Custom Toolbar Theme -->
<style name="mToolbarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
<!-- Toolbar 标题文字颜色 包括navigation search等icon颜色-->
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:padding">0dp</item>
</style>
<!-- Toolbar 弹出菜单样式 -->
<style name="mToolbarPopupTheme" parent="@style/ThemeOverlay.AppCompat.Light">
<!-- 菜单背景色 -->
<item name="android:colorBackground">@android:color/black</item>
<!-- 菜单文字色 -->
<item name="android:textColor">@android:color/holo_blue_dark</item>
<!-- 菜单字体 -->
<item name="android:textSize">20sp</item>
</style>
<!-- Toolbar 标题样式 -->
<style name="mToolbarTitle" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">14sp</item>
</style>
在AndroidManifest.xml中修改application theme
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/CAppTheme">
Toolbar布局
include_layout_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
style="@style/mToolbarStyle"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@android:color/holo_blue_bright"
app:popupTheme="@style/mToolbarPopupTheme"
app:theme="@style/mToolbarTheme"
app:titleTextAppearance="@style/mToolbarTitle">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@id/toolbar_left_view"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"/>
<ImageView
android:id="@id/toolbar_left_img"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_toRightOf="@id/toolbar_left_view"
android:scaleType="centerInside"
android:src="@drawable/ic_action_settings"
android:visibility="gone"/>
<TextView
android:id="@id/toolbar_left_tv"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_toRightOf="@id/toolbar_left_img"
android:gravity="center"
android:text="left_tv"
android:visibility="gone"/>
<TextView
android:id="@id/toolbar_center_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="@string/app_name"
android:textSize="16sp"
android:visibility="gone"/>
<ImageView
android:id="@id/toolbar_center_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxWidth="100dp"
android:visibility="gone"/>
<TextView
android:id="@id/toolbar_right_tv"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_toLeftOf="@id/toolbar_right_img"
android:gravity="center"
android:text="right"
android:visibility="gone"/>
<ImageView
android:id="@id/toolbar_right_img"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_toLeftOf="@id/toolbar_right_view"
android:scaleType="centerInside"
android:src="@drawable/ic_action_settings"
android:visibility="gone"/>
<View
android:id="@id/toolbar_right_view"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
BaseActivity布局
activity_base.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="@layout/include_layout_toolbar" />
</LinearLayout>
BaseActivity
public class BaseActivity extends AppCompatActivity {
private static final String TAG = "BaseActivity";
/**
* Root view
*/
private LinearLayout mRootLayout;
/**
* Toolbar instance
*/
protected Toolbar mToolbar;
public Toolbar getToolbar() {
return mToolbar;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_base);
if (!isTaskRoot()) {
/* If this is not the root activity,finish it.*/
Intent intent = getIntent();
String action = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
//Logger.w("Activity is not the root. Finishing Activity instead of launching.");
Log.w(TAG, "Activity is not the root. Finishing Activity instead of launching.");
finish();
return;
}
}
}
@Override
public void setContentView(int layoutId) {
setContentView(View.inflate(this, layoutId, null));
}
@Override
public void setContentView(View view) {
mRootLayout = (LinearLayout) findViewById(R.id.root_layout);
if (mRootLayout == null) {
return;
}
mRootLayout.addView(view,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
initToolbar();
}
/**
* 初始化Toolbar
*/
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
showToolbar(true);
//mToolbar.inflateMenu(R.menu.main);
/** 设置支持ActionBar,也可以不使用ActionBar */
//setSupportActionBar(mToolbar);
/** 去除ActionBar默认Title显示,可以不使用ActionBar */
// getSupportActionBar().setDisplayShowTitleEnabled(false);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//mToolbar.setNavigationOnClickListener(null);
}
}
/**
* 显示Toolbar
*
* @param show true:显示,false:隐藏
*/
public void showToolbar(boolean show) {
if (mToolbar == null) {
Log.e(TAG, "Toolbar is null.");
} else {
int paddingTop = mToolbar.getPaddingTop();
int paddingBottom = mToolbar.getPaddingBottom();
int paddingLeft = mToolbar.getPaddingLeft();
int paddingRight = mToolbar.getPaddingRight();
int statusHeight = ScreenUtil.getStatusHeight(this);
ViewGroup.LayoutParams params = mToolbar.getLayoutParams();
int height = params.height;
/**
* 利用状态栏的高度,4.4及以上版本给Toolbar设置一个paddingTop值为status_bar的高度,
* Toolbar延伸到status_bar顶部
**/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(show);
if (show) {
paddingTop += statusHeight;
height += statusHeight;
} else {
paddingTop -= statusHeight;
height -= statusHeight;
}
}
params.height = height;
mToolbar.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
mToolbar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
/**
* 设置透明状态栏
* 对4.4及以上版本有效
*
* @param on
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
获取状态栏高度
/**
* 获得状态栏的高度
*
* @param context
* @return px
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
overflowmenu
要使用overflowmenu,需要在res->menu中定义items,我们新建一个main.xml,内容如下:
<menu 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"
tools:context="com.elonlink.toolbardemo.MainActivity" >
<item
android:id="@+id/ab_search"
android:orderInCategory="10"
android:title="action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
app:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/action_settings1"
android:orderInCategory="100"
app:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
MainActivity布局
activity_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.elonlink.toolbardemo.MainActivity">
</RelativeLayout>
MainActivity
public class MainActivity extends BaseActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** 设置支持ActionBar,这样就能正常显示overflowmenu了,否则设置了menu也无法在Toolbar中显示和使用 */
setSupportActionBar(mToolbar);
/** 去除ActionBar默认Title显示*/
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(MainActivity.this,"action_settings!",Toast.LENGTH_SHORT);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
}
}
}