在自定义视图中扫描 Wifi

Scanning For Wifi Within Custom View

我有一个 android 应用程序,它有一个绘制网格的自定义视图。自定义视图只是主 activity 的 xml 文件的一部分。我需要能够根据用户选择的关联网格图块 (x,y) 扫描 wifi。我可以在自定义视图中使用 onTouchEvent 方法获得正确的网格图块,但我不知道如何将该信息返回到包含该视图的主 activity,因此我可以将 wifi 扫描与onTouchEvent 和选择的 x,y 图块。

如果我需要提供更多信息或任何代码,请告诉我。

编辑:

我会尽量简化这个问题。

我有一个 activity 其布局文件包含自定义视图。此自定义视图覆盖 onTouchEvent(),当在自定义视图中触发 onTouchEvent() 时,我需要将一些数据发送回 activity,然后使用自定义视图中的数据执行 wifi 扫描。

正如 Stefan 所建议的那样,自定义事件可能会有用,但我不确定在我的案例中如何实现。

使用自定义事件,您的代码将如下所示:

class CustomView : View {

    // define interface for your custom event
    interface MyCustomEvent {
        fun onGridTileClicked(x: Int, y: Int) // define your custom event
    }


    private var listener: MyCustomEvent? // define listener for your custom event

    /* in constructor of your custom view, you can register your activity to 
       listen for upcoming custom event, since you'll get context of your 
       activity here */
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.listener = context as? MyCustomEvent // register your activity as listener

        ...
    }

    override fun onTouchEvent(e: MotionEvent): Boolean {
        // get your x & y
        listener?.onGridTileClicked(x, y) // notify listener and pass x & y as arguments

        ...
    }

    ...
}

在你的activity中:

// implement custom event interface
class MyActivity : Activity, CustomView.MyCustomEvent {
    ...

    override fun onGridTileClicked(x: Int, y: Int) {
        // implement your logic
    }
}

编辑:

我的假设是您想将 xy 传递给 activity。当然,您可以传递任何您想要的数据。