繁体   English   中英

如何从Recycler-View适配器接收活动中的点击事件

[英]How to receive click event in activity from a recycler-view adapter

于14.11.2018编辑:

我想简化我的问题,如何从Fragment中获得一个click事件,该Fragment中包含一个recycler-view,它具有一个处理click事件的适配器?

该应用程序看起来如下: 在此处输入图片说明


我正在使用BLE服务的应用程序(基于Google BLE示例)。 我有一个DeviceScanActivity ,它能够成功搜索并连接到BLE外围设备,此活动启动一个新活动DeviceControlActivity ,并将BLE服务绑定到该活动:

@Override
protected void onStart() {
    super.onStart();
    Log.d(TAG, "onStart: bind Service. " + mServiceConnection);
    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}

在此活动中,我能够将值/消息发送到BLE外设。

我的应用程序还有另一个活动, ManualModeActivity 当我开始此活动时,如果是DeviceControlActivity,我首先将BLE服务解除绑定:

@Override
protected void onStop() {
    super.onStop();
    Log.d(TAG, "onStop: BLE Service is unbind " + mServiceConnection);
    unbindService(mServiceConnection);
    BLEServiceBonded = false;
}

然后,在新启动的活动( ManualModeActivity )中,将BLE服务绑定到它,就像在DeviceControlActivity的情况下一样。

现在开始出现问题,或者基本上我是android编程的新手,我不知道接下来应该怎么做才能在ManualModeActivity中使用BLE服务,因为搜索了两天,没有发现有用的信息。

因此,让我看看我无能为力,或者是什么使我面临挑战。

ManualModeActivity有一个带有两个选项卡的ViewPage,我创建了一个ManualTabPagerAdapter来扩展FragmentStatePagerAdapter,在此适配器中,我正在加载片段,例如ManualDeviceFrament 该片段具有RecyclerView,RecyclerView中的每个项目都有一个按钮,用于处理列表和按钮单击,我创建了ManualListAdapter 现在的挑战是,如果我单击按钮要发送BLE消息,但是BLE服务mBluetoothLeService为空。 我想使用以下命令发送消息:

mBluetoothLeService.writeCustomCharacteristic("Hello");

对于这两种活动,我都有以下代码来处理服务连接:

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        if (!mBluetoothLeService.initialize()) {
            Log.e(TAG, "Unable to initialize Bluetooth");
            finish();
        }
        mBluetoothLeService.connect(mDeviceAddress);
        BLEServiceBonded = true;
    }
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        BLEServiceBonded = false;
    }
}

伙计们,我想请您告诉我一些可能的解决方案,因为我没有找到任何有用的东西,我是一个新手,所以也许缺少一些基本知识。 如果您需要更多详细信息,请告诉我,我将在此处发布。

您是否还在ManualModeActivity上绑定和取消绑定服务? 关于重写onStop方法的另一件事,首先编写重写的代码比先调用父函数更好。 @Override protected void onStop(){unbindService(mServiceConnection); BLEServiceBonded =假; super.onStop(); Log.d(TAG,“ onStop:BLE服务已解除绑定” + mServiceConnection); }

暂无
暂无

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

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