Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add onclicklistener to dynamically generated text view?

In my application generating dynamic text view. I want to add onclickListener to my text view. How can I do it please give me some hint. Here hard code for textview .

        for (int i = 0; i < subCategory.length; i++) {
        TextView tv = new TextView(this);
        tv.setText(subCategory[i]);
        tv.setId(i);
        sCategoryLayout.addView(tv);

    }
like image 429
Narendra Avatar asked Jan 04 '12 05:01

Narendra


2 Answers

here is code :

TextView tv[] = new TextView[subCategory.length];
    for (int i = 0; i < subCategory.length; i++) {
            tv[i] = new TextView(this);
            tv[i].setText(subCategory[i]);
            tv[i].setId(i);
            sCategoryLayout.addView(tv[i]);
            tv[i].setOnClickListener(onclicklistener);
        }

onclicklistener method :

OnClickListener onclicklistener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v == tv[0]){
            //do whatever you want....
        }
    }
};

hope useful to you.

like image 199
Hiren Dabhi Avatar answered Nov 15 '22 20:11

Hiren Dabhi


for (int i = 0; i < subCategory.length; i++) {
        TextView tv = new TextView(this);
        tv.setText(subCategory[i]);
        tv.setId(i);
        tv.setOnClickListener(this);
        sCategoryLayout.addView(tv);

    }

@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
     switch(v.getId())
     {
     case 1:
     //Write Code For Click Here
     break;
     default:
     break;
    }
}

Impelement OnClickListner on this class.

like image 44
Khuswant Singh Avatar answered Nov 15 '22 19:11

Khuswant Singh