在我的Android项目中,有一个MainActivity.java
MainActivity extends FragmentActivity{
onCreate(Bundle savedInstanceState){
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
}
如何在下面的类中使用mBluetoothAdapter对象
public class AvailableDevices extends ListFragment {
// How to call mBluetoothAdapter here
}
谢谢
最佳答案
将其作为参数传递给类的构造函数
public class AvailableDevices extends ListFragment {
private BluetoothAdapter bluetoothAdapter;
public AvailableDevices(BluetoothAdapter bluetoothAdapter) {
this.bluetoothAdapter = bluetoothAdapter;
}
}
或将其声明为静态公共数据成员
public class MainActivity extends FragmentActivity{
public static BluetoothAdapter mBluetoothAdapter;
..
}
然后在另一个类中使用MainActivity.mBluetoothAdapter
或将AvailableDevices用作内部类,然后将适配器声明为数据成员:
public class MainActivity extends FragmentActivity{
private BluetoothAdapter mBluetoothAdapter;
..
class AvailableDevices extends ListFragment {
//can use mBluetoothAdapter
}
}