Search code examples
androidkotlinanko

Adding a swipe listener to textView in Anko


I'm looking to add swipe detection to a textView. I'm using Anko with Kotlin, and when it comes to setting up the textView, I'm able to specify an onClick event, but when I try to add an onTouch or any other gesture, it seems to fail for me (the fix-it just alternates between telling me to put stuff in parentheses and take it out again). I've included the code below and would appreciate any help!

        relativeLayout{

        //Title
        var title = textView{
            text = "Title Name"
            textSize = 24f

            onClick{
                if(caller.returnedData != ""){
                    startActivity<MainActivity>()
                }
            }

            onTouch {
                // code to recognise touch here
            }


        }.lparams{
            centerHorizontally()
            topMargin = dip(180)
        }

Solution

  • With Anko it's easy like a sharm:

    onTouch { view, event ->
    
                    // .. Respond to touch events
    
                    // put return value at the end:
                    true    // or view.onTouchEvent(event) to proceed other events
    }
    

    It's equal to the following Java code:

    myView.setOnTouchListener(new OnTouchListener() {
       public boolean onTouch(View v, MotionEvent event) {
          // ... Respond to touch events
          return true;
       }
    });