如何从一个类别中调用Object

时间:2014-10-20 12:04:48

标签: java android

在我的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 个答案:

答案 0 :(得分:1)

在类级别(在onCreate()方法之前)声明BluetoothManager bluetoothManager,其他类应该是内部类

答案 1 :(得分: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;


  }

答案 2 :(得分: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
    }
}