Reputation: 95
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
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