Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView - OnClick - Android

Is it possible to add onclick to some portion of a textview? For instance my code goes like this,

String content = "Hello this a test.. For more details contact @Peter";
someTextView.setText(content);

I would like to add an onClick event for "@Peter". Is that possible?

TIA.

like image 450
Naveen Avatar asked Jan 03 '13 08:01

Naveen


People also ask

Is onClick deprecated in Android?

onClick is prompted deprecated.

How can use onClick method in Android?

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

How will you add a click to a TextView and how is the route of the click set?

We will use this TextView to set on-click listener. Get reference to the the TextView in layout file using id, and then call setOnClickListener {} on this TextView. When user clicks on this TextView, the code inside setOnClickListener {} will be executed.


1 Answers

Simple: -)

SpannableString link = makeLinkSpan("@Peter", new View.OnClickListener() {          
        @Override
        public void onClick(View v) {
            // Peforme Click
        }
    });
String content = "Hello this a test.. For more details contact";
someTextView.setText(content);
someTextView.append(link);

And makeLinkSpan() method is

private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
    SpannableString link = new SpannableString(text);
    link.setSpan(new ClickableString(listener), 0, text.length(), 
        SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
    return link;
}

ClickableString Class

private static class ClickableString extends ClickableSpan {  
    private View.OnClickListener mListener;          
    public ClickableString(View.OnClickListener listener) {              
        mListener = listener;  
    }          
    @Override  
    public void onClick(View v) {  
        mListener.onClick(v);  
    }        
}
like image 72
user370305 Avatar answered Oct 04 '22 15:10

user370305