我正着手为我的应用程序创建一个设置 Activity 。我定义了一个 PreferenceActivity
,它的布局很好,包括一个 ListPreference
对象,供用户选择蓝牙设备。 我在动态填充列表时遇到问题。
我想用数组适配器中的值填充 ListPreference
(我将创建并用相关的蓝牙设备名称填充)。
如果这是一个旋转 View ,我可以调用 setAdapter()
。但是,对于 ListPreference
对象,我不知道如何附加适配器(findviewByID
不会从 View 转换为 ListPreference
,所以我甚至无法获得对象的句柄)。
我想附加一个适配器,然后用值填充适配器,这反过来会用值填充 ListPreference
。
最佳答案
对于蓝牙设备列表的特殊情况,您可以使用以下类:
package de.duenndns;
import android.bluetooth.*;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
import java.util.Set;
public class BluetoothDevicePreference extends ListPreference {
public BluetoothDevicePreference(Context context, AttributeSet attrs) {
super(context, attrs);
BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bta.getBondedDevices();
CharSequence[] entries = new CharSequence[pairedDevices.size()];
CharSequence[] entryValues = new CharSequence[pairedDevices.size()];
int i = 0;
for (BluetoothDevice dev : pairedDevices) {
entries[i] = dev.getName();
if (entries[i] == null) entries[i] = "unknown";
entryValues[i] = dev.getAddress();
i++;
}
setEntries(entries);
setEntryValues(entryValues);
}
public BluetoothDevicePreference(Context context) {
this(context, null);
}
}
它可以直接从您的首选项 XML 中参与,将 MAC 存储为首选项字符串:
<de.duenndns.BluetoothDevicePreference
android:key="bluetooth_mac"
android:title="Bluetooth Device"
android:dialogTitle="Choose Bluetooth Device" />
关于android - 是否可以从适配器加载 ListPreference 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2936919/