I dynamically created buttons through code rather than from XML.
The code is as below :
dynamicview = (LinearLayout)findViewById(R.id.llayout);
LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<nob;i++){
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
I am not finding a way in which I can implement OnClickListener to each of these buttons so that I can perform action based on the reference I get.
Can anyone help me in sorting out this issue. ?
Thanks in Advance,
See the code below:
My example is pretty simple, but demonstrates how you can get the button index into the
OnClickListeber
. You can access anyfinal
field in the declared anonymous classes (e..g theOnClickListener
).its the same thing...
}
And add this listner outside the any method and inside class
Use a
List
and addButton
s you create to thatList
Now add your button to that List
Then use advanced for loop to iterate through the list and add click listener for each Button..
Maybe this will be helpful for somebody I wanted to use the one counter variable for group of dynamically created buttons:
I've created the array for counters:
From preferences I've taken the quantity of elements:
And finally we create the buttons