Skip to content Skip to sidebar Skip to footer

Single Onclick Listener For Multiple Textviews Created Programmatically In Android

So I have successfully created a number of textviews programmatically using the below piece of code that I have written. I would like to create an efficient single listener for the

Solution 1:

Just create a listener and assign it to your views like you would any other attribute.

OnClickListenerl=newOnClickListener(){
    publicvoidonClick(View v){
        // TODO whatever...
    }
}

for(i=0 ; i < optionCubesTextviews.length; i++) {
    optionCubesTextviews[i].setTag(i);
    optionCubesTextviews[i].setOnClickListener(l);
}

Solution 2:

Check this example i made and I hope it helps you :)

In this way you can check which view clicked.

publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  // THIS IS MY MAIN LAYOUTLinearLayoutlinearLayout= (LinearLayout) findViewById(R.id.main_layout);

    for (inti=0; i < 3; i++) {
        TextViewtextView=newTextView(this);
        textView.setTag(String.valueOf(i));
        textView.setOnClickListener(this);
        textView.setText("TEXT VIEW " + i);
        linearLayout.addView(textView);
    }
}

@OverridepublicvoidonClick(View view) {
    switch (view.getTag().toString()) {
        case"0":
            Toast.makeText(this, "TEXT VIEW 1", Toast.LENGTH_LONG).show();
            break;
        case"1":
            Toast.makeText(this, "TEXT VIEW 2", Toast.LENGTH_LONG).show();
            break;
        case"2":
            Toast.makeText(this, "TEXT VIEW 3", Toast.LENGTH_LONG).show();
            break;
        default:
            Toast.makeText(this, "Default", Toast.LENGTH_LONG).show();
    }
}}

Post a Comment for "Single Onclick Listener For Multiple Textviews Created Programmatically In Android"