Search code examples
androidtextviewclickable

Make clickable textview in android


By this way i have showed ids from DB.

TextView setNote = (TextView) findViewById(R.id.idNotes);
setNote.setText("");  //empty current text

//DB connection
DatabaseHandler db = new DatabaseHandler(this);


List<Contact> contacts = db.getAll();

for (Contact cn : contacts) 
{
  Integer id = cn.getID();

  setNote.append(id.toString()+"\n");        
}

RESULT

12

35

42

Now i want to make these ids clickable such that when user clicks on each id, it will open a separate activity corresponding to this id. How can i do this?


Solution

  • If you want to make the whole TextView clickable then you can just add an onClickListener as others have mentioned.

    However, if you want to make each of the ID's you're printing clickable separately (ie. each one goes somewhere else), you'll have to create add your own Span class.

    Here's an example implementation. First define your own span by extending from ClickableSpan:

    static class MyClickableSpan extends ClickableSpan {  
        OnClickListener mListener;  
    
        public MyClickableSpan(OnClickListener listener) {  
            mListener = listener;  
        }  
    
        @Override  
        public void onClick(View widget) {  
            mListener.onClick(widget);  
        }  
    }  
    

    Next, you want to create a SpannableString for each of the id's you print:

    for (Contact cn : contacts) {
       String id = cn.getID().toString();
       SpannableString mySpan = new SpannableString(id+"\n")  
       mySpan.setSpan(new MyClickableSpan(new OnClickListener() {  
           public void onClick(View v) {  
              //Do whatever you want when clicked here! <----  
           }  
         }), 0, id.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
       setNote.append(mySpan);        
    }
    

    Finally, to enable clicking, you need to add the LinkMovementMethod to your TextView as follows:

    // Put this at the end after finishing your for-loop
    setNote.setMovementMethod(LinkMovementMethod.getInstance());
    

    This will allow you to make each of the ID's clickable where each one goes to a separate Activity if that's what you want