简体   繁体   中英

ClickableSpan AND onClickListener on TextView

I need to have both on a TextView: When the TextView is clicked, trigger a function. But when a certain part of the text is clicked, trigger a different function.

So I have a ClickableSpan for that certain part, and an OnTouchListener on the whole TextView:

SpannableString string = new SpannableString(input);
// ...
string.setSpan(new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        functionOne();
    }
}, start, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(string);

// ...

textView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }
});

Both work fine for themselves:

If I do not add the OnTouchListener, it calls functionOne() , triggered from the ClickableSpan.

But if I also add the OnTouchListener, it only calls gestureDetector.onTouchEvent(event) . Also if I click on the certain part of the text, where the ClickableSpan should be triggered.


How can I have both?

So that if the certain part is clicked, the ClickableSpan is triggered, and if a different part of the text is clicked, then gestureDetector.onTouchEvent(event) is called.

Try this below function to achieve clickable span and there is no need to call touch listener. click event will be handled by ClickableSpan.

 fun setClickableSpan(
    spannable: Spannable,
    paths: ArrayList<String>,
    listener: EventListener
) {
    for (i in paths.indices) {
        val indexOfPath = spannable.toString().indexOf(paths[i])
        if (indexOfPath == -1) {
            continue
        }
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(textView: View) {
                listener.onItemClick(textView, i, paths[i])
            }
        }
        spannable.setSpan(
            clickableSpan, indexOfPath,
            indexOfPath + paths[i].length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM