【发布时间】:2016-10-06 07:46:12
【问题描述】:
这是我的第一个 Android 应用程序,所以也许这是一个愚蠢的问题。所以,请考虑我是否做错了。
我正在构建一个与蓝牙相关的应用。
我的MainActivity.java 中有一个方法:
public void showDeviceListDialog() {
BluetoothDeviceListDialog dialog = new BluetoothDeviceListDialog(this);
dialog.setOnDeviceSelectedListener(this);
dialog.setTitle("Paired Devices");
dialog.setDevices(bluetoothSerial.getPairedDevices());
dialog.showAddress(true);
dialog.show();
}
我需要从另一个片段调用这个方法。所以,当我这样调用这个方法时:MainActivity.showDeviceListDialog(); 它要求制作方法 Static。但是当我把它 Static 我在“this” [ dialog.setOnDeviceSelectedListener( 上遇到错误这个);]关于我的方法。
我已经阅读了一些帖子,例如 this 和 this,但我的问题没有得到帮助。
我已经从我的片段中尝试过这个:
MainActivity mc = new MainActivity();
mc.showDeviceListDialog();
但这显示的是 NullPointerException。
所以,请告诉我如何从我的片段中调用它而不会出现此错误。 谢谢。
【问题讨论】:
-
您可以使用接口作为活动的回调。永远不要
MainActivity mc = new MainActivity(); -
你不能实例化你的活动
-
您不能将
this与static一起使用。您也不应该在扩展Activity的类上使用new -
@Blackbelt 显然你可以做到,但这并不意味着你应该这样做
-
伙计们,这不是重复的。尽管问题似乎与
static方法的用法有关,但他提出的解决方案实际上并不涉及创建静态方法。这是从 Fragment 访问活动的问题。