如何从另一个类调用对象 [英] How to call Object from one class other

查看:165
本文介绍了如何从另一个类调用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid项目有一个MainActivity.java

In my Android project there is a MainActivity.java

MainActivity extends FragmentActivity{

    onCreate(Bundle savedInstanceState){

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

    }
  }

如何使用mBluetoothAdapter对象在下面的类

How to use mBluetoothAdapter object in the below class

public class AvailableDevices extends ListFragment {

     // How to call mBluetoothAdapter here
  }

感谢

推荐答案

把它作为参数传递给类的构造函数

pass it as a parameter to the constructor of the class

public class AvailableDevices extends ListFragment {
   private BluetoothAdapter bluetoothAdapter;
   public AvailableDevices(BluetoothAdapter bluetoothAdapter) {
       this.bluetoothAdapter = bluetoothAdapter;
   }
}

或声明为静态公共数据成员

or declare it as a static public data member

public class MainActivity extends FragmentActivity{

    public static BluetoothAdapter mBluetoothAdapter;

    ..
 }

和然后在其他类使用MainActivity.mBluetoothAdapter

and then in the other class use MainActivity.mBluetoothAdapter

,或使AvailableDevices一个内部类,并声明该适配器作为数据成员:

or make the AvailableDevices an inner class and declare the adapter as a data member:

public class MainActivity extends FragmentActivity{

    private BluetoothAdapter mBluetoothAdapter;
    ..
    class AvailableDevices extends ListFragment {
         //can use mBluetoothAdapter
    }
}

这篇关于如何从另一个类调用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆