Search code examples
androidkotlinandroid-custom-viewandroid-wifi

Scanning For Wifi Within Custom View


I have an android app that has a custom view that draws a grid. The custom view is only a section of the main activity's xml file. I need to be able to scan for wifi based on an associated grid tile (x,y) that the user selects. I'm able to get the correct grid tile using the onTouchEvent method in the custom view but I don't know how to get that information back to the main activity that contains the view so I can relate a wifi scan with the onTouchEvent and with the x,y tile that was selected.

Let me know if I need to provide any more info or any code.

Edit:

I'll try and simplify the question a little bit.

I have an activity whose layout file contains a custom view. This custom view overrides onTouchEvent() and when the onTouchEvent() is triggered in the custom view I need to send some data back to the activity and then perform a wifi scan using the data from the custom view.

As Stefan suggested a custom event might be useful, but I'm unsure of the implementation in my case.


Solution

  • Using custom event, your code would be something like this:

    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
    
            ...
        }
    
        ...
    }
    

    And in your activity:

    // implement custom event interface
    class MyActivity : Activity, CustomView.MyCustomEvent {
        ...
    
        override fun onGridTileClicked(x: Int, y: Int) {
            // implement your logic
        }
    }
    

    Edit:

    My assumption is that you want to pass x and y to activity. Of course, you can pass any data you want.