下面是一个示例的 BluetoothAdapter 类的实现:

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class BluetoothAdapter extends ArrayAdapter<BluetoothDevice> {

    private Context mContext;
    private int mResource;

    public BluetoothAdapter(@NonNull Context context, int resource, @NonNull List<BluetoothDevice> devices) {
        super(context, resource, devices);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            view = inflater.inflate(mResource, null);
        }

        BluetoothDevice device = getItem(position);
        if (device != null) {
            TextView nameTextView = view.findViewById(android.R.id.text1);
            TextView addressTextView = view.findViewById(android.R.id.text2);

            if (nameTextView != null) {
                nameTextView.setText(device.getName());
            }

            if (addressTextView != null) {
                addressTextView.setText(device.getAddress());
            }
        }

        return view;
    }
}

在这个 BluetoothAdapter 类中,我们重写了'getView'方法,在这个方法中设置了每个列表项的显示内容。我们使用'LayoutInflater'从指定的布局文件创建视图对象,然后通过'findViewById'找到布局中的 TextView,最后设置显示的文字。注意,这里使用了'device.getName()'和'device.getAddress()'来获取蓝牙设备的名称和地址。

在你的代码中,你可以使用下面的方式来实例化和使用这个 BluetoothAdapter 类:

List<BluetoothDevice> devices = ...; // 获取蓝牙设备列表
BluetoothAdapter adapter = new BluetoothAdapter(context, android.R.layout.simple_list_item_2, devices);
ListView listView = ...; // 获取 ListView 对象
listView.setAdapter(adapter);

这样就可以将蓝牙设备列表显示在 ListView 上了,每个列表项的 text1 显示设备名称,text2 显示设备地址。

Android 蓝牙设备列表适配器:BluetoothAdapter 类实现

原文地址: https://www.cveoy.top/t/topic/o6vB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录