Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set onclick events on textview created programmatically

I create clickable textview dynamically depending on the records retrieved from the database just like this.

DBAdapter db = new DBAdapter(this);

db.open();
Cursor c = db.getAllProfiles();
if(c.moveToFirst())
{
    do{
        TextView tv = new TextView(this);
        tv.setText(c.getString(1));
        tv.setTextSize(18);
        tv.setTextColor(Color.BLACK);
        tv.setClickable(true);
        tv.setPadding(0, 10, 0, 0);
        tv.setGravity(Gravity.CENTER);
        mainLayout.addView(tv);

        tv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
        Toast.makeText(getBaseContext(), tv.getText().toString(), Toast.LENGTH_LONG).show();
            }
        });

    }while(c.moveToNext());
}
else
    Toast.makeText(getBaseContext(), "No Profiles", Toast.LENGTH_LONG).show();
db.close();

How can I set click events on each texview independently? On the way I see it, if I create a click event on the loop, the click event might get triggered by all textviews.

*Update tried adding events in every loop but got this error:

"cannot refer to a non-final variable inside an inner class defined in a different method".

like image 695
Luke Villanueva Avatar asked Dec 10 '12 09:12

Luke Villanueva


2 Answers

change your code as to add OnClickListener to TextView

TextView tv;
     if(c.moveToFirst())
            {
                do{
                    tv = new TextView(this);
                    tv.setText(c.getString(1));
                    tv.setTextSize(18);
                    tv.setTextColor(Color.BLACK);
                    tv.setClickable(true);
                    tv.setPadding(0, 10, 0, 0);
                    tv.setGravity(Gravity.CENTER);
                    tv.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // do you work here
                     }
                    });
                    mainLayout.addView(tv);

                }while(c.moveToNext());
            }
like image 139
ρяσѕρєя K Avatar answered Oct 20 '22 02:10

ρяσѕρєя K


use this

do{
                TextView tv = new TextView(this);
                tv.setText(c.getString(1));
                tv.setTextSize(18);
                tv.setTextColor(Color.BLACK);
                tv.setClickable(true);
                tv.setPadding(0, 10, 0, 0);
                tv.setGravity(Gravity.CENTER);
                tv.setId(1)
                tv.setOnClickListner(this);
                mainLayout.addView(tv);

            }while(c.moveToNext());

and put a onClick method as below

    @Override
public void onClick(View v)
{
    if(v.getId()==1)
    {

        // do stuf here
    }
    }
like image 33
Sanket Kachhela Avatar answered Oct 20 '22 02:10

Sanket Kachhela