Android custom view set onClickListener with navigation

Viewed 296

I've created a custom view that should be a button, but i can't quite get it to work.

So my custom view is extended from View, and I need to to make a fragment navigation when clicked

I've tried to use the override fun performClick() and in it do a rootView.findNavController().navigate(R.id.action_menu_to_settings) but it crashes. I also tried use the .setOnClickLister() { // navigation } but it also doesn't work.

Can anyone tell me how set a clickListener on a custom view for a navigation? Thx

1 Answers

If you are creating a custom view, the best way to handle the click operations is like this:

class MyView @JvmOverloads constructor (
  context: Context,
  attrs: AttributeSet? = null,
  defStyleRes: Int = 0,
  defStyleAttr: Int = 0
) : View(context, attrs, defStyleRes, defStyleAttr) {
  
  var touchType = -1 // No user touch yet.

  var onClickListener: () -> Unit = { 
    Log.d(TAG, "on click not yet implemented")
  }

  override fun onDraw(canvas: Canvas?) {
    /* your code here */
  }

  override fun onTouchEvent(e: MotionEvent?): Boolean {
    val value = super.onTouchEvent(e)

    when(e?.action) {
      MotionEvent.ACTION_DOWN -> {
        /* Determine where the user has touched on the screen. */
        touchType = 1 // for eg.
        return true
      }
      MotionEvent.ACTION_UP -> {
        /* Now that user has lifted his finger. . . */
        when (touchType) {
          1 -> onClickListener()
        }
      }
    }
    return value
  }
}

And in your client class (Activity/Fragment), with the instance of the specific custom view that you instantiated, apply the following:

myView.onClickListener = {
  findNavController().navigate(R.id.action_menu_to_settings)
}
Related