Search code examples
androidkotlinviewtouch-event

Dispatch touch event to view drawn on canvas


I'm making a custom view on which I can add items (images, text, etc.) and drag them around, as well as scaling and rotating. Now I'd like to add an entire view to that canvas. I used the draw(canvas) method of View and it works. However, I can't interact with that view, e.g. for instance if it has a button I cannot click it, even though I'm passing the touch events to that view. I'm kind of doing this:

val mySubView = LayoutInflater.from(context).inflate(R.layout.item, null)

// mySubView is passed to CustomView at some point
class CustomView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mySubView.draw(canvas)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val handled = mySubView.onTouchEvent(event)
        return handled || super.onTouchEvent(event)
    }
}

Any ideas ? Thanks!


Solution

  • You won't be able to interact with the view you draw on canvas. You don't add it into the layout 'android style', you draw it manually - this means you will need to manually figure out if user clicks on the drawn buttons based on the click position and button drawn position, manually invoke selectors(you will need to redraw selector usage manually also) and manually invoke corresponding methods. It is not very good way to do such stuff on android since you will miss out almost all the android ui framework features and you will have to implement them manually.

    The thing is you are drawing picture of a view but not the view itself - this is the problem.