繁体   English   中英

从Android片段类访问抽象方法的类组织

[英]Class organization to access abstract method from Android fragment class

我不能确定我的问题陈述是什么,正如你可以从标题中看出来的那样。 我有一个扩展Activity的抽象类A. A类定义了一个抽象方法:

public abstract class A extends Activity {
    ActionBar.Tab devicesTab, otherTab;
    Fragment fragmentTab = new FragmentTab();

    protected abstract void connectBluetooth(BluetoothDevice deviceToConnect);
}

实现connectBluetooth(BluetoothDevice 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);
    }
}

内部类AI有一个Fragment,它有自己的类,类FragmentTab扩展Fragment。 此类包含允许用户选择要连接的设备的UI。 我需要将该设备传递给A类或访问connectBluetooth(BluetoothDevice deviceToConnect),以便主要活动可以从它开始。 我尝试过使用“包装”方法,但它总是导致方法需要是静态的,这不允许我使用connectBluetooth(BluetoothDevice deviceToConnect),因为它是一个抽象的受保护方法。

我该怎么做才能解决这个问题? 它需要另一堂课吗? 或者我只是错过了什么?

谢谢!

我需要从Fragment创建一个事件回调到我的活动。 在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调用在A类中实现的OnDeviceSelected方法。

...  mDeviceListener.onDeviceSelected(deviceToConnect);

实现该方法的A类必须具有“implements”描述:

public abstract class A extends Activity implements FragmentTab.OnDeviceSelectedListener
{   ...
} 

最后是A类中的实现:

public void onDeviceSelected(BluetoothDevice deviceToConnect)
{
    connectBluetooth(deviceToConnect);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM