user1448108
user1448108

Reputation: 487

How to write onclick actions for dynamically generated textviews in android?

I have to display the textviews dynamically in android and need to write onclick action for each textview. I am able to display the textviews dynamically but I didnt get how to write the onclick action for each textview. Please help me regarding this...Will be thankful to you..

Upvotes: 1

Views: 513

Answers (2)

Nuno Gonçalves
Nuno Gonçalves

Reputation: 6805

Create the views dinamically however you want to do and add the listener right then.

TextView tv = new TextView(ActivityName.this);
tv.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       Toast.makeText(ActivityName.this, "tv text: " + ((TextView) v).getText().toString()).show();
       //Do whatever you want to do here.
    }
});
layout.addView(tv); //layout added on the xml for example, or by an inflater.

Upvotes: 0

Omer KAPLANDROID
Omer KAPLANDROID

Reputation: 1105

You should check this code. Create an onclicklistener and then use setOnClickListener(); method.

private TextView textview1, textview2;  
//initialize them       

OnClickListener customTextviewOnClicklistener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
             if (v == textview1)
            {
                // Here your code for textview1
                Log.i("Clicked Item", "textview1"); 
            }  
            else if (v == textview2)
            {
                // Here your code for textview2
                Log.i("Clicked Item", "textview2");  
            }
            else
            {
                //Here your code for others
            }
        }
    };

    textview1.setOnClickListener(customTextviewOnClicklistener);
    textview2.setOnClickListener(customTextviewOnClicklistener);

i hope this may help you.

Upvotes: 2

Related Questions