Search code examples
androidtextviewrowclickable

Retrieve TextView clicked row number


Really stupid question here, but could not find an answer googling.

I have a clickable textview. How to retrieve the row's number that is clicked??


Solution

  • The question isn't that stupid because there is no built-in method, that I know of, to do this.

    However you can use:


    Basic example:

    textView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                float line = FloatMath.floor(event.getY() / textView.getLineHeight());
                Toast.makeText(getBaseContext(), "" + line, Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });
    

    From the getLineHeight() documentation:

    Note that markup within the text can cause individual lines to be taller or shorter than this height, and the layout may contain additional first- or last-line padding.

    So if you have modified any attribute listed above, you'll need to account for that as well.