My program asks a user to enter their name and click on a button called btn. Once btn is clicked, their name is dynamically added to a TableRow along with another dynamically created Button. It's these Buttons that I'm having an issue with. I need to somehow access them later on in the program. I created a number of IDs in my res/value folder to keep track of each one(changebtn1, changebtn2, etc..). They're all stored in an array called buttonIDs.
Let's say that the user enters the first name, a new row is created with a dynamically created button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tableRow = new TableRow(getApplicationContext());
Button changeButton = new Button(getApplicationContext());
changeButton.setText("Change");
changeButton.setId(buttonIDs[i]);//From res/values
tableRow.addView(changeButton);
tableLayout.addView(tableRow);
i++;
});
Now let's say they enter a second name, another Button is created and so on and so forth. How can I now set an OnClickListener to my first Button that I created, which has the ID of R.id.changeBtn1? In other words, I have all of these dynamically created buttons and am not sure how to add OnClickLsteners() to earlier ones or access them in anyway. Thank you
Or you attach the OnClickListener directly in the creation of the button or you can store the references to the buttons like this:
ArrayList<Button> buttons = new ArrayList<Button>();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tableRow = new TableRow(getContext());
Button changeButton = new Button(getContext());
buttons.add(changeButton);
changeButton.setText("Change");
changeButton.setId(buttonIDs[i]);//From res/values
tableRow.addView(changeButton);
tableLayout.addView(tableRow);
i++;
});
for(Button button: buttons){
button.setOnClickListener(new OnClickListener()
...etc...
);
}
You won't waste a lot of memory since the buttons.add() line won't copy the button in the array but just the reference to the button. If you need a in id access to the buttons, use an HashMap, like this:
HashMap<String, Button> map = new HashMap<String, Button>();
map.put("id", new Button(getContext()));
And then access it like this:
Button button = map.get("id");
How about something like this
for(int i=0;i<buttonIDs.size();i++) {
Button currentButton = (Button) findViewById(buttonIDs[i]);
currentButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Stuff
}
});
}
I did not check the code
#filnik The first part of your answer also gave me an idea. I created an OnClickListener method outside of my OnCreate() method.
View.OnClickListener changeTeamName(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
//Do Stuff
}
};
}
I then set an OnClickListener to EACH dynamically created Button and use the method that I created.
changeButton.setText("Change");
changeButton.setTag("ButtonOne");
changeButton.setOnClickListener(changeTeamName(changeButton));
The fact that each Button now has an OnClickListener associated with it, they can now perform whatever function I add to my method.
Related
From this code it creates dynamic buttons accodring to a given value from another layout. I need to get the id of that and add another button (if dynamic button clicks then I need to add another button dynamically).
for (int i = 0; i < value1; i++) {
LinearLayout.LayoutParams paramsIButton = new LinearLayout.LayoutParams
((int) ViewGroup.LayoutParams.WRAP_CONTENT, (int) ViewGroup.LayoutParams.WRAP_CONTENT);
ibutton = new ImageButton(HomePage.this);
ibutton.setImageResource(R.drawable.add);
ibutton.setLayoutParams(paramsIButton);
paramsIButton.topMargin = -70;
paramsIButton.leftMargin = 370;
paramsIButton.bottomMargin = 30;
ibutton.setId(i);
ibutton.getPaddingBottom();
ibutton.setBackgroundColor(Color.WHITE);
ibutton.setAdjustViewBounds(true);
rR.addView(ibutton);
}
If I understood correctly from the additional information you provided on your comment, you need to know when a user clicked on a button. You could set an OnClickListener to your button.
// Somewhere in your activity . . .
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// The button is clicked! Do whatever you want.
}
});
}
// ...
// Rest of the code
// ...
Of course, you should replace R.id.button1 with your button's id.
Seems to me like you need to add an onClickListener for the dynamically added button.
Make your class implement OnClickListener and then add a listener for the dynamic button:
ibutton.setOnClickListener(this);
and add an onClick Listener within your class:
#Override
public void onClick(View v)
{
// do something with this ID
v.getId()
}
I don't know how you keep track of the bulbs and fans, I'd hope you don't do it via the UI elements alone. I'd probably do it a bit differently, creating a data structure to track the bulbs and fans and attach the specific bulb or fan object to the UI element as a tag.
I am populating a table dynamically from a string array.Each row of the table also has a plus and minus button to increment/decrement the value of one column. These buttons are also dynamically created like in the code below. Here how can I detect the exact button upon clicking. i.e; if I click on the '+' button of the 2nd row, how can I get the id of the button clicked for further processing.
plusButton= new Button(this);
minusButton= new Button(this);
createView(tr, tv1, names[i]);
createView(tr, tv2, (String)(names[i+1]));
minusButton.setId(i);
minusButton.setText("-");
minusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
plusButton.setId(i);
plusButton.setText("+");
plusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));`
You can set an onClickListener listener for each button. Use the id of the button from view.getId() method on your onClick() method to identify the button click.
You can add separate listeners for each button like here (assuming that the id you are setting for each button corresponds to a row)
minusButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// Do some operation for minus after getting v.getId() to get the current row
}
}
);
Edit:
I am assuming your code is like this. Correct me if there is a deviation.
Button minusButton = null;
for(int i = 0; i < rowCount; i++)
{
minusButton = new Button(this);
minusButton.setId(i);
// set other stuff and add to layout
minusButton.setOnClickListener(this);
}
Let your class implement the interface View.OnClickListener and implement the onClick() method.
public void onClick(View v){
// the text could tell you if its a plus button or minus button
// Button btn = (Button) v;
// if(btn){ btn.getText();}
// getId() should tell you the row number
// v.getId()
}
You could do with tags: minusButton.setTag("-") and plusButton.setTag("+").
In your clickListener just get it from your button with view.getTag().
Then switch between your actions comparing the string tag.
Edit:
ID's "should" be unique. The setTag() method may help you if setId() doesn't work for you.
I am trying to do this:
Programatically create 4 buttons on a layout. Then, create an onclick listener for each of the button. Then, based on which button is pressed, will do some logic.
I have created a LinearLayout in my XML file and called it "layout".
So, my codes go something like this:
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// if it is the first button, do LOGIC1
// if it is the second button, do LOGIC2 etc
}
});
}
So far, I have managed to create the 4 buttons and I can click on the buttons.
However, I do not know how to the logic in the setOnClickListener part.
I wanted to know which button is pressed. So, I tried using v.getId() but it always returns a -1.
Can someone advise if this is the right way to go? And if so, how to do the logic?
Thanks.
You have two options for identify which dynamic button is clicked.
1) Set ID to the button and compare ID
2) Set Tag to the button if you have come more information about button
and want to access it
1) You can set id to the button and in onClick() method you can get id by button.getId() method and you can compare ids and perform action according to click.
2) If you set tag then you have to get tag by calling button.getTag() method and by this way you can pass object with the button
You can set the id of the buttons after you create them, and then check for that id within the OnClickListener
layout = (LinearLayout)findViewById(R.id.layout);
//Create the array of buttons
Button [] subjectButtons_BT = new Button[4];
for(int i=0; i<4; i++){
subjectButtons_BT[i] = new Button(this);
subjectButtons_BT[i].setId(i);
// Add the button to the layout
layout.addView(subjectButtons_BT[i]);
subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int id = v.getId();
if (id == 0) {
} else if (id == 1) {
}
//etc.
}
});
}
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
I'm creating buttons dynamically ...
for(int i=0; i<colSize;i++){
final Button btn = new Button(this);
btn.setText(SectionName[i]);
btn.setTextSize(10);
btn.setPadding(8, 3,8, 3);
btn.setTextColor(Color.WHITE);
btn.setTypeface(Typeface.SERIF, Typeface.BOLD);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//***Every time that I click my button is selected !:)
btn.setSelected(true);
}
});
}
But how could I deselect the other buttons that were selected, I just want one Button selected! :)
The brutal way (works if you have few buttons) - save your button references and create private method which loops through your buttons and deselects once you don't need
Extend your button class and make it listen for custom event which is generated when one of the buttons is clicked
Look at the RadioGroup implementation
Variation of #1. Instead of creating separate listeners for your buttons create just one and reuse it for all buttons. Extend that listener from OnClickListener and add List field. Each time you assign listener to the button add button reference to that list. Now, when onClick is triggered simply loop through the list and disable "other" buttons
Declare a variable to store the Id of the Clicked Button ::
private int EnabledButton;
set an ID on every button when are created ::
btn.setId(i);
or a tag ::
btn.setTag(i);
then in that Listener get the "EnabledButton", and call a function to deselect the other buttons::
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EnabledButton=btn.getId();
DeselectButtons();
btn.setSelected(true);
}
});
The Function to deselect the other Buttons ::
public void DeselectButtons() {
for(int i=0; i<NumberofButtons;i++){
if (EnabledButton!= i)
this.findViewById(i).setSelected(false);
}
}