ActionBar的使用
1.获取ActionBar
android-support-v4使用getSupportActionBar()
android-support-v7使用getActionBar()
ActionBar actionBar = getActionBar();
如果此时的actionBar为null
原因:问题是由Activity基类引起的,当使用AppCompatActivity或其他support包中的基类,那么获得ActionBar实例需要用另一个相应的方法,那就是getSupportActionBar(),ActionBar也要使用相应support包下的。
应改为:
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
2.自定义ActionBar
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setCustomView(R.layout.actionbar);//设置自定义的布局:actionbar_custom
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //Enable自定义的View
actionBar.setDisplayShowCustomEnabled(true);
}
R.layout.actionbar.xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
>
<TextView
android:id="@android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="更多"
android:textSize="20dp"
android:textColor="@color/white"/>
</RelativeLayout>
4.消除自定义ActionBar两侧的空白部分
主要原因是ActionBar里的ContentInsetSart和ContentInsetEnd属性要设置为0dp
解决办法:1.在stytle.xml中加入以下代码
<!--actionbar 两侧留有空白 -->
<style name="AppActionbar" parent="Theme.AppCompat.Light">
<item name="windowActionBar">true</item>
<item name="actionBarStyle">@style/ClubActionbar</item>
<item name="android:windowNoTitle">true</item>
<item name="android:cursorVisible">true</item>
</style>
<style name="ClubActionbar" parent="Widget.AppCompat.ActionBar">
<item name="contentInsetStart">0dp</item><!-- 设置该属性解决左侧空白部分-->
<item name="contentInsetEnd">0dp</item><!-- 设置该属性解决右侧空白部分-->
</style>
2.在manifest.xml中设置主题
<activity
android:name=".ui.AttentionActivity"
android:configChanges="keyboardHidden|orientation"
android:label="@string/attention"
android:theme="@style/AppActionbar" <!-- <span style="color:#FF0000;"><strong>添加此处</strong></span>-->
android:screenOrientation="portrait" />
5.隐藏
6.去除ActionBar
在style.xml文件中修改
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
修改为
Theme.AppCompat.NoActionBar或ThemeAppCompat.Light.NoActionBar这两种主题即可