2014-10-20 54 views
0

在我的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 
    } 

感谢

+3

'BluetoothManager bluetoothManager =(BluetoothManager)getActivity()。getSystemService(Context.BLUETOOTH_SERVICE);' – EpicPandaForce 2014-10-20 12:08:58

回答

0

传递作为参数的类

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 
    } 
} 
+0

这是对MainActivity的一种丑陋而完全不必要的依赖。如果使用static或singleton对象,我至少将它保存在一个单独的类中。我个人使用Dagger做依赖注入,但在许多情况下,我猜可能会矫枉过正。 – cYrixmorten 2014-10-20 12:35:48

1

申报在类级别(在onCreate()方法之前)的BluetoothManager bluetoothManager和其他类应该是内部类

+0

如果我声明为类成员如何使用其他类 – Shiv 2014-10-20 12:12:05

+0

其他类应该是内部类。或者,您可以使用全局变量/ pakage进行管理 – 2014-10-20 12:18:38

1
There are two ways known to me- 

Using Static variable: 

MainActivity extends FragmentActivity{ 
public static BluetoothAdapter mBluetoothAdapter; 
    onCreate(Bundle savedInstanceState){ 

     BluetoothManager bluetoothManager = 
       (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
     mBluetoothAdapter = bluetoothManager.getAdapter(); 

    } 
    } 

public class AvailableDevices extends ListFragment { 

    // How to call mBluetoothAdapter here 
    use in this class as MainActivity.mBluetoothAdapter 

    } 


2.Passing mBluetoothAdapter to the constructor of the second class. 

MainActivity extends FragmentActivity{ 

    onCreate(Bundle savedInstanceState){ 

     BluetoothManager bluetoothManager = 
       (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
     mBluetoothAdapter = bluetoothManager.getAdapter(); 

    } 
    } 

public class AvailableDevices extends ListFragment { 
    BluetoothAdapter mBluetoothAdapter=null; 
AvailableDevices(BluetoothAdapter mBluetoothAdapter){ 
    this.mBluetoothAdapter=mBluetoothAdapter; 


    }