ActionBar的使用

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这两种主题即可
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值