2

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));
}
1
  • Do you want to create array of Buttons ? Also do you want to define separate onClickListener for each button in the array? Is that what you are looking for? Commented Jul 27, 2013 at 3:51

2 Answers 2

1

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 
}
Sign up to request clarification or add additional context in comments.

Comments

0

Just make your categoryName and categoryID arrays be final.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.