<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:id=“@+id/item_device”
android:background=“?android:attr/selectableItemBackground”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”>
<LinearLayout
android:gravity=“center_vertical”
android:padding=“12dp”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”>
<ImageView
android:id=“@+id/iv_device_type”
android:src=“@mipmap/icon_bluetooth”
android:layout_width=“30dp”
android:layout_height=“30dp”/>
<TextView
android:id=“@+id/tv_name”
android:paddingLeft=“12dp”
android:textSize=“16sp”
android:text=“设备名称”
android:textColor=“#000”
android:layout_width=“0dp”
android:layout_weight=“1”
android:layout_height=“wrap_content”/>
<TextView
android:gravity=“right”
android:id=“@+id/tv_bond_state”
android:text=“绑定状态”
android:layout_width=“0dp”
android:layout_weight=“1”
android:layout_height=“wrap_content”/>
<View
android:background=“#EBEBEB”
android:layout_marginLeft=“54dp”
android:layout_width=“match_parent”
android:layout_height=“1dp”/>
一切准备工作都已经就绪了,下面就进入编码环节,前面的内容其实和Kotlin的关系都不大,下面上正菜,Kotlin相比于Java来说的优势就是简洁,这一点会在下面的编码过程中体现。
1. 通知栏样式修改
首先修改状态栏的文字颜色,如果你现在运行这个项目在手机上时,你会发现状态栏是白色的背景以及白色的文字。如下图所示:
这样的用户体验是很不好的,而在Android6.0以后支持设置高亮状态栏样式。在之前我写Java版的时候特别弄了一个工具类,里面有针对性状态栏的一些样式和颜色改动,但实际上我只用了其中的一个方法,为了一个方法而去写一个工具类显然多此一举了。所以在Kotlin中我想到了更简单的办法,直接在MainActivity中修改状态栏样式。
代码如下:
//设置亮色状态栏模式 systemUiVisibility在Android11中弃用了,可以尝试一下。
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
放在onCreate方法中,然后运行。
是不是立竿见影,这个效果一行代码解决问题还不用写工具类,完全调用系统的方法,请注意我是Android10.0版本的手机,也是我自己用的手机。
下面写列表的适配器,因为你扫描蓝牙肯定会是一个列表,既然是一个列表那么肯定要有适配器。
2. 蓝牙设备列表适配器编写
创建一个adapter包,包下创建一个DeviceAdapter.kt文件,如下所示
DeviceAdapter的代码如下:
package com.llw.bluetooth.adapter
import android.bluetooth.BluetoothClass
import android.bluetooth.BluetoothClass.Device.*
import android.bluetooth.BluetoothClass.Device.Major.*
import android.bluetooth.BluetoothDevice
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.llw.bluetooth.R
/**
- 蓝牙设备适配器
*/
class DeviceAdapter(layoutResId: Int, data: MutableList?) :
BaseQuickAdapter<BluetoothDevice, BaseViewHolder>(layoutResId, data) {
override fun convert(helper: BaseViewHolder?, item: BluetoothDevice?) {
val tvName = helper!!.getView(R.id.tv_name)
val icon = helper.getView(R.id.iv_device_type)
//根据设备类型设置图标
getDeviceType(item!!.bluetoothClass.majorDeviceClass, icon)
tvName.text = if (item.name == null) “无名” else item.name
//蓝牙设备绑定状态判断
val tvState = helper!!.getView(R.id.tv_bond_state)
tvState.text = when (item.bondState) {
10 -> “未配对”
11 -> “正在配对…”
12