Java 从Android片段类访问抽象方法的类组织
我真的不确定我的问题陈述是什么,正如你从标题中可以看出的那样。我有一个扩展活动的抽象类A。类A定义了一个抽象方法:Java 从Android片段类访问抽象方法的类组织,java,android,android-fragments,abstract-class,abstract-methods,Java,Android,Android Fragments,Abstract Class,Abstract Methods,我真的不确定我的问题陈述是什么,正如你从标题中可以看出的那样。我有一个扩展活动的抽象类A。类A定义了一个抽象方法: public abstract class A extends Activity { ActionBar.Tab devicesTab, otherTab; Fragment fragmentTab = new FragmentTab(); protected abstract void connectBluetooth(BluetoothDevice d
public abstract class A extends Activity {
ActionBar.Tab devicesTab, otherTab;
Fragment fragmentTab = new FragmentTab();
protected abstract void connectBluetooth(BluetoothDevice deviceToConnect);
}
实现connectBluetooth(Bluetooth设备deviceToConnect)的类扩展了类A:
public class MainActivity extends A {
@Override
protected void connectBluetooth(BluetoothDevice deviceToConnect)
{
Intent intent = new Intent(this, bActivity.class);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, deviceToConnect);
this.startActivity(intent);
}
}
在类A中,我有一个片段,它有自己的类,类FragmentTab扩展了片段。此类包含允许用户选择要连接的设备的UI。我需要将该设备传递给class A或访问connectBluetooth(蓝牙设备deviceToConnect),以便主要活动可以从它开始。我尝试过使用“包装器”方法,但它总是导致方法需要是静态的,这不允许我使用connectBluetooth(Bluetooth设备deviceToConnect),因为它是一种抽象保护的方法
我能做些什么来解决这个问题?它需要另一门课吗?还是我错过了什么
谢谢 我需要从片段中创建一个对我的活动的事件回调。在Simon的评论之后,谢谢Simon,我研究了接口和回调。这解决了我的问题,但我同意设计可以返工 在FragmentTab类中,我需要一个接口:
OnDeviceSelectedListener mDeviceListener;
public interface OnDeviceSelectedListener
{
public void onDeviceSelected(BluetoothDevice deviceToConnect);
}
此外,需要将其附加到活动:
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mDeviceListener = (OnDeviceSelectedListener)activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnDeviceSelectedListner");
}
}
之后,OnItemClickListener调用OnDeviceSelected方法,该方法在类A中实现
... mDeviceListener.onDeviceSelected(deviceToConnect);
实现该方法的类A必须具有“implements”描述:
public abstract class A extends Activity implements FragmentTab.OnDeviceSelectedListener
{ ...
}
最后是驻留在类A中的实现:
public void onDeviceSelected(BluetoothDevice deviceToConnect)
{
connectBluetooth(deviceToConnect);
}
你需要重新考虑你的设计。只有另一个
活动
应该扩展活动
。不能将活动视为POJO,框架必须控制其生命周期。从阅读界面
开始。使用回调可能是您想要的。我应该说,在使用片段之前,对connectBluetooth(BluetoothDevice deviceToConnect)的调用是从类a内部进行的,因此没有任何问题,但我需要使用片段分离UI,从而找到要在片段类内部连接的设备。现在我不能把那个“设备”带回A类了@Simon是对的。你需要重新思考你的设计。我只需要创建一个singletonBluetoothUtil
类。只需在方法参数中添加一个上下文
对象,并使用该对象代替此
@sonictt1,这非常危险。将上下文传递给singleton。将该上下文设置为活动
参考。旋转你的设备,砰的一声,瞬间内存泄漏。@Simon说得对。我会对那个可能的解决方案提出更正,但OP找到了她的解决方案,所以我不想麻烦了。