I need to get the id of the dynamically generating button - android

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.

Related

Using Mutliple Dynamically Created Buttons in Android

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.

Android calculator buttons

I am trying to make a calculator for Android. Here is the code for my buttons:
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextValue = (EditText) findViewById(R.id.editText1);
TVValue = (TextView) findViewById(R.id.textView1);
buttons = new ArrayList<Button>();
for(int id : button_ids) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
buttons.add(button);
}
}
How I can change this part to a block of code where I won't have to declare the IDs of the buttons? (e.g. R.id.BtnNum0)
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
I have been searching for an answer, but I still can't find a solution.
What you can do, since this code seems to only set a single OnClickListener for all Buttons, is to do it in xml
For each Button set
android:onClick="functionName"
then in your code you can do away with all of the id's and your for loop. In Java just create a function like
public void functionName(View v)
{
switch (v.getId())
{
case R.id.buttonId:
// do work for this Button
break;
...
}
The way you are doing it is fine but this is how I prefer to handle this situation. You just have to give all of the Buttons the same function name in xml then use that name as your function name in Java. You also just have to be sure to declare the function with a void return type and make sure it takes a View as its one and only parameter as in my example.
The Button Docs also have an example of this
in your layout file add this to every button
<Button
...
android:onClick="btnClicked"
.../>
then in your code add this method and check for each button in this method
public void btnClicked(View v)
{
switch(v.getId())
{
case R.id.BtnNum0:
// your code
break;
....
}
}
That is likely the best solution unfortunately, unless you use some sort of annotation framework which still doesn't cut down much on the boilerplate.
edit:
You could try to get a pointer to whatever ViewGroup is holding the Button views and then getting all of its children, and then looping through them while casting them to Buttons as you go.
For example: If your Button objects in XML are housed in a LinearLayout, you could get the pointer to that and do something like this:
for(int i=0; i < ((ViewGroup)v).getChildCount(); ++i) {
Button nextChild = (Button) ((ViewGroup)v).getChildAt(i);
}
Of course, I recommend against this, but it is still a possibility.
As trevor-e suggested, you can give an annotation processor a try. Android Annotations can simplify your code to:
#Click
public void BtnNum0() {
// Button 0 clicked
}
#Click
public void BtnNum1() {
// Button 1 clicked
}
// etc.
If you go this route, please do try to use names following the Java convention as the button names correspond with function names.

How to manage setOnClickListener on a array of buttons

I have a dynamic array of buttons and I would like to know how to handle the onclick on every button?
Thanks
I don't see a need to create a new OnClickListener for each button -- all the buttons could share a single listener.
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
Object tag = v.getTag();
// Do something depending on the value of the tag
}
};
...
for (int i=0; i < btns.length; ++i) {
btns[i].setOnClickListener(myListener);
btns[i].setTag(some_identifying_information);
}
Of course, you could create a unique OnClickListener for each button, and take advantage this way:
for (int i=0; i < btns.length; ++i) {
final Button btn = btns[i];
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something depending on the value of btn, which you're allowed
// to reference here because it was declared final above.
}
});
}
The same way you would on a single button...
Set an on click listener, if you have an Array it would look something like this:
btns[0].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
btns[1].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
//etc.
If you want all of them to do the same thing you could use a for loop to loop over the array like this:
for(int i = 0; i< btns.length; i++){
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
}
I don't know exactly what you are doing but if you have an Array of Buttons it is likely that you should probably be using an Adapter with a ListView or something instead of how every you are doing it now.
Without seeing some code or more of an explanation, it's hard to really answer your question, but here are some tips:
Before we get to the listeners, we have to make sure that each of the dynamically created buttons knows how to respond to a click event. You can use the setTag method on a button to attach an arbitrary Object to it. This Object will represent how the Button acts when clicked. You can just use Integers as this Object (perhaps some constant values) or if each button needs some unique data, create a class that maintains both how the button needs to act when clicked AND the data you need (or at least a reference to it).
Then, you can initialize one single listener that handles all of your button clicks. In the onClick method of this listener place a conditional that branches to handle all of your click cases. Set this listener on all of your dynamic buttons as you create them. At the start of your onClick, get the Tag from the View parameter of the onClick method (this view will be the button that was clicked), and use that to decide which branch of the conditional to take.
Hope this helps. If you make your question more specific, we'll be able to offer some more detailed assistance.

Some alternative to hundreds of buttons

Im going to write some android app, which will basically consists of two activities. So first should have a lot of buttons (100+) and on click on any of them I will just get some special id and move to second activity. But is there any alternative to declare that hundreds of buttons and copy/paste one piece of code to every of them setting almost same onClickLister? Is there any special construction? Thanks
Edit: every of buttons are actually indexed from 1 to n. And on the click second activity will be launched and get that index to show it. I cant basically use any spinner or smth else, because there will be 3 rows of clickable things and each of them carring different images
Edit 2: so, to give you an idea, im going to do some table of buttons like in Angry Birds menu when you actually choosing the level you want to play. So, on click you will get id of button and start second activity
Call the method to add buttons
private void addButton(){
LinearLayout view = (LinearLayout) findViewById(R.id.linear_layout_id_here);
Button btn = null;
int w = 50;
int h = 25;
for(int i=1; i<100; i++) {
btn = new Button(this);
btn.setLayoutParams(new LayoutParams(w,h));
btn.setText("button " +i);
btn.setTag(""+i);
btn.setOnClickListener(onClickBtn);
view.addView(btn);
btn = null;
}
}
Call this method for handling onclick on button
private View.OnClickListener onClickBtn = new View.OnClickListener() {
public void onClick(View view) {
final int tag = Integer.parseInt(view.getTag().toString());
switch (tag) {
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
default:
break;
}
}
};
You should use a ListView.
ListViews are great for handling a lot of items at the same time. They are also natural for the user. Additionally, you use only one click listener - OnItemClickListener.
There's a useful example on how to work with ListViews in the Android Referenence.
You may add buttons in code, something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
/*your code here*/
GroupView gw =findViewById(R.id.pnlButtonscontainer); //find the panel to add the buttons
for(int i=0; i<100; i++) {
Button b = new Button(this);
b.setLayoutParameters(new LayoutParameters(w,h));
b.settext = i+"";
b.setOnClickListener(new OnClickListener(){
});
}
}
I coded directly into browser, so some syntax error may appear in my code, but this is the point, a way, not the only one, to add 100 buttons.

Android: Knowing which button is pressed for buttons that are created programatically

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.
}
});
}

Categories

Resources