我正在制作所有有限蓝牙设备的单一选择列表。一旦做出选择,我会尝试举报“成功”的消息。 我的projekt中有2个文件。 MainActivity.java:
import package_name.DeviceChooser.listenForDeviceChoose;
public class MainActivity extends ActionBarActivity implements listenForDeviceChoose{
public void chooseDevice (View view) {
deviceArray.clear();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
deviceArray.add(device.getName());
}
}
DeviceChooser deviceChooser = new DeviceChooser();
deviceChooser.show(getSupportFragmentManager(), "DeviceChooser");
}
}
和DeviceChooser.java:
public class DeviceChooser extends DialogFragment {
public interface listenForDeviceChoose {
public void clickDevice(int i);
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setSingleChoiceItems(cs, 1,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((listenForDeviceChoose) builder).clickDevice(which);
}
});
}
}
当我做出选择时,应用程序崩溃了。为什么?我在哪里可以学到所有这些小东西?
答案 0 :(得分:0)
您发布的代码段会引发ClassCastException
因为MainActivity
实现了接口。您应该转换活动的对象而不是Dialog的构建器。
((listenForDeviceChoose) getActivity()).clickDevice(which);