Android 蓝牙开发 周边设备列表 实现步骤
1. 创建 展示list单个列表的item
<?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="44dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/text_title"
android:textSize="18sp"
android:text="你好"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
2. 创建 listview 的xml 文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ListView
android:id="@+id/home_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
3. 挂着listview
View myview = inflater.inflate(R.layout.fragment_home, container, false);
listView = myview.findViewById(R.id.home_list_view);
listView.setOnItemClickListener(this);
listView.setAdapter(homeListAdapter);
return myview;
4. 加载item
@SuppressLint("MissingPermission")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HanderView handerView;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.home_device_layout, parent, false);
TextView textView = convertView.findViewById(R.id.text_title);
handerView = new HanderView();
handerView.textView = textView;
convertView.setTag(handerView);
}else {
handerView = (HanderView) convertView.getTag();
}
BluetoothDevice device = peripheralList.get(position);
handerView.textView.setText(device.getName());
return convertView;
}
private class HanderView {
TextView textView;
}
5. 更新数据刷新
public void setPeripheralList(List<BluetoothDevice> peripheralList) {
this.peripheralList = peripheralList;
notifyDataSetChanged();
}
效果:
img_v2_1819dd56-b61b-4ce8-8b3d-e806d39e84eg.jpg
网友评论