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".
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());
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With