Home » Java » Android, How can I get text from TextView in OnClick

Android, How can I get text from TextView in OnClick

Posted by: admin December 28, 2021 Leave a comment

Questions:

I have some TextView and each have an OnClickListener. I would like get information in this method to TextView

TextView tv2 = new TextView(this,(String)book.get(i),this);
tv2.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        Intent intent = new Intent(Contact.this,Discution.class);
        //String str = this.getText(); //like this
        startActivity(intent);
    }
});

How can I do : this.getText(); in an OnClickListener ?

Answers:

This is wrong

TextView tv2 = new TextView(this,(String)book.get(i),this);

You will need TextView to be final and the constructor should match any of the below

TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyle)

It should be

final TextView tv2 = new TextView(this);

You are not using any of the above. Totally wrong

Then inside onClick

String str = tv2.getText().toString();  

Its declared final cause you access tv2 inside annonymous inner class.

http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing

You can also use the View v.

TextView tv = (TextView) v;
String str = tv.getText().toString();  

###

tv2.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
    Intent intent = new Intent(Contact.this,Discution.class);

            String str = tv2.getText().toString(); 

            startActivity(intent);
}

###

Just use: tv2 in place of this.

###

Use this

tv2.getText().toString;

###

Lets suppose you have this in your layout:

<TextView android:id           ="@+id/myText"
          android:layout_width ="wrap_content"
          android:layout_height="wrap_content"
          android:textSize     ="26dp"
          android:text         ="bla bla bla..."
          android:textColor    ="#0000ff"
          android:clickable    ="true"
          android:onClick      ="onMyClick"/>

Now lets get the text content from myText element when it gets clicked

public void onMyClick(View v)
     {
     TextView t=(TextView)v;
     String s=t.getText().toString();
     //do whatever you want with the string s
     }

Note the boolean android:clickable="true" on the layout element [ it’s mandatory ]