Welcome to Ray's Blog

Stay Hungry Stay Foolish - Steve Jobs

0%

ActionBar知识笔记


ActionBar 知识点:

  1. setHomeButtonEnabled这个小于 4.0 版本的默认值为 true 的。但是在 4.0 及以上的是 false,该方法的作用:决定左上角的图标是否可以点击。没有向左的小图标。true:图标可以点击,false 不可以点击;

  2. actionBar.setDisplayHomeAsUpEnabled(true)给左上角图标的左边加上一个返回的图标。对应 ActionBar.DISPLAY_HOME_AS_UP;

  1. mActionBar.setDisplayShowHomeEnabled(true) 使左上角图标是否显示,如果设成 fasle,则没有程序图标,仅仅就一个标题,否则,显示应用程序图标,对应 id 为 Android.R.id.home,对应:ActionBar.DISPLAY_SHOW_HOME;

  2. `mActionBar.setDisplayShowCustomEnabled(true) 事自定义的普通 View 能在 title 栏显示,即 mActionBar.setCustomView 能起作用,对应 ActionBar.DISPLAY_SHOW_CUSTOM;

  3. `mActionBar.setDisplayShowTitleEnabled(true) 对应 ActionBar.DISPLAY_SHOW_TITLE。

  4. 其中 setHomeButtonEnabled 和 setDisplayShowHomeEnabled 共同起作用,如果 setHomeButtonEnabled 设成 false,即使 setDisplayShowHomeEnabled 设成 true,图标也不能点击。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 设置是否显示ActionBar左上角返回按钮
* @return
*/
protected boolean isHomeUp() {
return true;
}
/**
* ActionBar设置
*/
protected void initActionBar() {
mActionBar = getSupportActionBar();
if (mActionBar != null) {
mActionBar.setDisplayShowHomeEnabled(isHomeUp());//是否显示左上角返回图标
mActionBar.setDisplayHomeAsUpEnabled(isHomeUp());//左上角图标是否可以点击
}
}
/**
* @return boolean Return false to allow normal menu processing to
* proceed, true to consume it here.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

设置 Actionbar.setTitle()标题,则会覆盖原应用名称显示,如图:

设置自定义 View

1
2
mActionBar.setDisplayShowCustomEnabled(true);//显示自定义View
mActionBar.setCustomView(R.layout.actionbar_custom_view01);//自定义View

** 如果设置了自定义 View,那么 ActionBar title 则会被自定义 view 占据位置 **

  1. 如何计算 ActionBar 高度:
1
2
3
4
5
6
7
8
9
10
11
/**
* 计算ActionBar高度
*/
private void calActionBarHeight(Context mContext) {
// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics());
Log.i(TAG, "calActionBarHeight: actionBarHeight="+actionBarHeight);
}
}

ActionBar 的隐藏方式

使用代码隐藏

  1. getSupportActionBar().hide(); //隐藏掉整个 ActionBar;
  2. 在 Activity 中setContentView之前设置requestWindowFeature(Window.FEATURE_NO_TITLE);即可;

使用配置隐藏

  1. 在需要隐藏的 Activity 的AndroidManifest.xml文件中设置主题
1
2
<activity android:name=".activity.CoordinatorLayoutSampleActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
1
2
3
4
<style name="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>