bluebl1
bluebl1

Reputation: 176

How do I get a string from the OnClickListener View? Android

I set up quite a few TextViews in a for loop, and each one gets .setClickable(true)

Then, I

tv.setOnClickListener(new OnClickListener() { //tv is the TextView.
    public void onClick(View v) {

    }
});

I know that it's a TextView, but I'm given View v. How do I get the text of the TextView from inside public void onClick(View v){ }? Remember: I can't simply make tv a final because it's in a for loop and it makes a lot of TextViews.

Upvotes: 0

Views: 1025

Answers (3)

user2780486
user2780486

Reputation: 1

    @Override
public void onClick(View v) 
    { 
    String text = null;
if(v instanceof TextView)
    {
     TextView t = (TextView) v;
         text = t.getText().toString();
    }

    //this is for sending our clicked edittext value to next page ...

Intent next=new Intent(getApplicationContext(),sendSMS.class);
next.putExtra("msg",text);
startActivity(next);

    }

Upvotes: 0

Abhishek Nandi
Abhishek Nandi

Reputation: 4275

You can typecast the view to a textView and get the text. You can add a tag to the TextView and simply call v.getTag()

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34367

Can you typecast as below?

        public void onClick(View v) {
            String text = null;
            if(v instanceof TextView){
                TextView t = (TextView) v;
                text = t.getText().toString();
            }
        }

Upvotes: 2

Related Questions