Kasun Gunathilaka
Kasun Gunathilaka

Reputation: 95

Create buttons from StringArray and set onClickListener

I have to get the array and use it to dynamically create onClickListener(). I have used this method to create dynamic buttons. Anyone has any idea how to use an array to dynamically create onClickListener()?

for (int i = 0; i < categoryName.size(); i++) {

    Button btn = new Button(this);
    btn.setId(Integer.parseInt(categoryID.get(i).toString()));
    btn.setHint(categoryID.get(i).toString());
    btn.setText(categoryName.get(i)); //another array with the name of the IDS
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //example
            Toast.makeText(getApplicationContext(),categoryID.get(i),Toast.LENGTH_LONG).show();
        }
    });
    buttonLayout.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}

Upvotes: 2

Views: 1258

Answers (2)

E-Kami
E-Kami

Reputation: 2669

Just make your categoryName and categoryID arrays be final.

Upvotes: 0

Bhoomika Brahmbhatt
Bhoomika Brahmbhatt

Reputation: 7415

Put only btn.setOnClicklistener(this); instead of

btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        //example
        Toast.makeText(getApplicationContext(),categoryID.get(i),Toast.LENGTH_LONG).show();
    }
}); 

onClick():

@Override
public void onClick(View v) {
    //example
    //you can check its view 
    //here V gives you BtnId 
}

Upvotes: 1

Related Questions