安卓APP开发之自定义标题栏

    对于新手,要自定义标题栏也是个坑来的,自己摸索了很久,总算有了点模样出来了。

    先看图片


第一张是改之前的标题栏,第二张是改之后的,下面详细说明修改标题栏涉及到的关键点

1,AndroidMainifest.xml

    必须更改:5颗星

    修改android:theme,创建工程时,加载了默认的主题,如果要自定义标题栏,就要自己定义主题文件

<application android:label="@string/app_name"
    android:icon="@drawable/logobluetooth"
    android:theme="@style/TileTheme">
    <activity android:name=".FirstActivity"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <service android:name=".BluetoothLeService" android:enabled="true"/>
</application>

TIleTeme放在 .xml文件里面

mythmythem.xml

<?xml version="1.0" encoding="utf-8"?>
<resources >
    <style name="TileTheme" parent="android:Theme.Light">
        <item name="android:windowTitleSize">35dp</item>
        <item name="android:windowContentOverlay">@color/noncolort</item>
        <item name="android:windowTitleBackgroundStyle">@style/TileBackground</item>
    </style>
    <color name="noncolort">#00000000</color>
    <style name="TileBackground">
        <item name="android:background">@drawable/drawabletitle</item>
    </style>
</resources>

这个只是主题样式,就是你的APP的界面的显示效果,比如显示背景

具体的标题栏里的内容需要建一个layout文件,可以放按键Button,menu,图片image等控件

title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center_vertical"
    >
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:id="@+id/tv_title"
            android:text="我的标题"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/bt_titleBk"
            android:background="@color/color_Backup"
            android:text="返回"
            />
</LinearLayout>
这些准备工作做好后,就可以加载自定义标题了

public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE)//获取自定义标题栏权限
    setContentView(R.layout.devicescan)
    window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.tile)//加载自定义标题栏

    }

特别说明,

获取自定义标题栏权限,要放在setcontentView之前,

然后再调用自定义标题文件,

大功告成……

猜你喜欢

转载自blog.csdn.net/linqiping233/article/details/80451668