Creating Buttons Dynamically, Could I select one and deselect the other buttons? - android

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

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.

using two buttons out of twelve at once

I have 12 buttons in my activity..i want to use them in the following way:
Two buttons should be allowed to click at once and when those two are clicked then some action to be performed..if this action is successful, these two buttons must be "invisible" and if this action is unsuccessful, again there must be option to click any of the two buttons out of all twelve..
i have set the layout of this activity and all the twelve buttons as well.I have also set the onClick method for all of the buttons.
[ADDITION]
i mean only two out of twelve buttons be allowed to press at once..any two of them..and after that the output of both the buttons be compared..if they are equal then the buttons be invisible else they are still there and once again the user gets a chance to click two buttons..
[CODE]
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
RotateAnimation rotate = new RotateAnimation(0,90);
rotate.setFillAfter(true);
button1.startAnimation(rotate);
Random r = new Random();
int next = r.nextInt(5) + 1;
imgV1.setImageResource(images[next]); //imageView1 is given a random image
AlphaAnimation alpha = new AlphaAnimation(0,1);
alpha.setFillAfter(true);
imgV1.startAnimation(alpha);
arg0.clearAnimation();
}});
imgV1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlphaAnimation alpha = new AlphaAnimation(1,0);
alpha.setFillAfter(true);
imgV1.startAnimation(alpha);
RotateAnimation rotate = new RotateAnimation(90,0);
rotate.setFillAfter(true);
button1.startAnimation(rotate);
arg0.clearAnimation();
}});
button click gives a random image..image click gives the button back..now i want that when two buttons are clicked and if they have the same image, then they both go invisible..else they both turn back to the buttons and user can again click on any of the two buttons..
Each button has an imageView behind it in the layout..
K.. Now I got it. So, there will be 6 images in your Drawable. Here we go..
Make an Integer array of size 12 to store id's of 6 images. say, int[] images={R.drawable.img1,...};
Also Button firstClick;Drawable back; to know the first clicked button.
Now, our onClick will be as,
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(count<2){// means first click
firstClick=(Button)v;
back=v.getBackground();
action=images[0];// button1 pressed so index 0
v.setBackgroundResource(action);
v.setEnabled(false);
count++;
}
else{//second click
count=0;
if(action==images[0]){
v.setBackgroundResource(action);
v.setEnabled(false);
}else{
v.setBackgroundDrawable(back); //roll back to old background
firstClick.setBackgroundDrawable(back);
}
}
}
});
You can use setVisibility() method of view(Button) to set it's visibility on or off.
Button b = ( Button )findViewById( R.id.button1 );
b.setVisibility( b.INVISIBLE );
b.setVisibility( b.VISIBLE );
The logic that I thought is like,
You should have two variables in hand globally.
1 for counting button clicks and 2nd for storing first click action(Based upon your app).
I'm taking int action=0,count=0; as global variables.
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(count<2){// means first click
action=1;// button1 pressed
count++;
}
else{//second click
count=0;
//Here perform your action and based upon it, set visibility. Previous click is available in 'action'
}
}
});
Repeat this for all button clicks. Thats it. I'll prefer your own method to be called for perform actions and set visibility.

How to identify the button clicked from a dynamically generated table

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.

How to enable a button after a certain button is clicked?

Here is the scenario : I have a gui which contains two buttons.Now is there any way by which second button is clickable only after first button is clicked ?
say you have activity with two buttons defined in the xml layout : button1 and button2
in activity onCreate method write:
button2.setEnabled(false);
In the in click listener of first button write
button2.setEnabled(true);
so finally
in onCreate method of the activity we have
button2.setEnabled(false);
private OnClickListener l = new OnClickListener() {
public void onClick(View v) {
button2.setEnabled(true);
}
};
button1.setOnClickListener(l);

Android Multiple Buttons with different Actions

I create buttons dynamically based on the size of an array list that i get from another object. For each entry of the arraylist i need to create three buttons each one with different action.
Like this i need to create 3 times the sizes of arraylist number of buttons. If i had only one set of buttons I can write onClick()-method which takes the id of the button but here i have 3 buttons for each entry and need to write 3 different actions for those three buttons.
How could this be done?
Similar thing I have done when i needed a textview for each of my array item.it was like-
String[] arrayName={"abc","def","ghi"};
for(int i=0;i<arrayName.length;i++)
{
TextView tv=new TextView(context);
tv.setPadding(20, 5, 40, 5);
tv.setText(arrayName[i]);
tv.setTextSize(1, 12);
tv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setTextColor(Color.parseColor("#2554C7"));
tv.setClickable(true);
tv.setId(i);
layout.addView(tv);
}
In same way,you can add button in similar way. and in click event of each of them,you can code for their actions separately.(I have not tried this).So in each iteration,you will have 3 buttons for each of the array item.
Edit - 1:
You can differentiate ids like:
mButton1.setId(Integer.parseInt(i+"1"));
mButton2.setId(Integer.parseInt(i+"2"));
mButton3.setId(Integer.parseInt(i+"3"));
Then you can set click listener on each of the button like mButton1.setOnClickListener... and so on.
Declare a list of buttons:
private List<Button> buttons = new ArrayList<Button>();
Then add each button to this list:
buttons.add(0, (Button) findViewById(id in ur layout));
Inside a for loop give click listener:
Button element = buttons.get(i);
element.setOnClickListener(dc);
where dc is ur object name for your inner class that implements OnClickListener.
To access each button you can give:
Button myBtn;
#Override
public void onClick(View v) {
myBtn = (Button) v;
// do operations related to the button
}
Create the Common Listener class for your button action event and set the used into the setOnClickListener() method
Now set the unique id for the buttons.
Now suppose your class look like this :
class MyAction implements onClickListener{
public void onClick(View view){
// get the id from this view and set into the if...else or in switch
int id = view.getId();
switch(id){
case 1:
case 2:
/// and so on...
}
//// do operation here ...
}
}
set this listener in button like this way.
Button b1 = new Button(context);
b1.setId(1);
b1.setOnClickListenr(new MyAction());
Button b2 = new Button(context);
b2.setId(2);
b2.setOnClickListener(new MyAction());

Categories

Resources