Here i am creating 20 Button dynamically using for loop
exmple
for(int i =1 ;i <= 20 ;i++){
Button b = new Button(this);
b.setText(String.valueOf(i));
b.setId(String.valueOf(i));
b.setBackgroudColor(Color.Red);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
b.setBackgroundColor(Color.GREEN);
}
);
}
If i select 1st Button color will be changing to green remaining all are red. similarly if i select 2nd Button 1st and 2nd button color will be green and remaining all are red. this is the way it working fine .but my requirement is if i select the any button 2nd time all buttons and previous button which i pressed color should be red. to do that i am not getting the previous button id's. can any help for this problem
Hold a reference of the previously pressed button:
final Button prevButton;
for(int i =1 ;i <= 20 ;i++){
Button b = new Button(this);
b.setText(String.valueOf(i));
b.setId(String.valueOf(i));
b.setBackgroudColor(Color.Red);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(prevButton != null)
prevButton.setBackgroundColor(Color.RED);
b.setBackgroundColor(Color.GREEN);
prevButton = (Button)v;
}
);
}
Are you sure using 20 Buttons is a good choice?
Can you use GridView?
You can change the backGroundColor as well: forums.pragprog.com/forums/152/topics/10301
Related
In my android project in one screen I have a button and a separate object that has a black background. When I click the button the separate objects color should change to white and the next click it should change to yello, then orange then red.
I have searched for weeks trying to find something to help my project with android studio and java on a windows 7 pc. Thanks in advance for any help
The code in your activity should look like this:
int counter = -1;
int[] colors = {0xffffffff, 0xffffff00, 0xffff6600, 0xffff0000, 0xff000000};
Button buttonColored;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
buttonColored = (Button) findViewById(R.id.buttonColored);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
if (counter > colors.length - 1) {
counter = 0;
}
buttonColored.setBackgroundColor(colors[counter]);
}
});
}
buttonColored is a button to be colored when clicking button
counter is a variable that takes all the values from 0 to 4, incremented every time button is clicked and reset to 0 when it is 5
I have ten buttons and only one of them has a Red background at any point of time and the red button has an onClicklistener.
When this red button is clicked one of these ten buttons in random will get red background and this new red button should use the previous onCLickListener and when this new red button is clicked again one of these ten buttons in random gets red background and the onClickListener should be assigned to it and there is a counter which counts every time the RedButton is clicked.
Example:
There are four buttons
[WhiteButton WhiteButton RedButton WhiteButton] and only RedButton has onClickListener
when RedButton is clicked one of the buttons color changes to red
[WhiteButton RedButton WhiteButton WhiteButton]
when this new RedButton is clicked the buttons become
[WhiteButton WhiteButton WhiteButton RedButton]
I am able to change the color of one of the ten buttons to red when the RedButton is Clicked for the first time but not able to set the OnClickListener to the new RedButton.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ourButton = (Button) findViewById(R.id.button);
ourTextView = (TextView) findViewById(R.id.textView);
buttons[0] = (Button) findViewById(R.id.button2);
buttons[1] = (Button) findViewById(R.id.button3);
buttons[2] = (Button) findViewById(R.id.button4);
buttons[3] = (Button) findViewById(R.id.button5);
Random r = new Random();
oddValue = r.nextInt(4 - 0);
buttons[oddValue].setBackgroundColor(Color.RED);
buttons[oddValue].setOnClickListener(new ourOnClickListener(this));
ourOnClickListener
public class ourOnClickListener implements OnClickListener{
MainActivity caller;
private int count;
public ourOnClickListener(MainActivity activity) {
this.caller = activity;
this.count = 0;
}
public void onClick(View view) {
int i;
count = count + 1;
Random r = new Random();
int oddValue_new = r.nextInt(4 - 0);
caller.buttons[oddValue_new].setBackgroundColor(Color.RED);
caller.ourTextView.setText("Count : " + count);
}
}
You can do it the same way as you set the background color:
caller.buttons[oddValue_new].setOnClickListener(this);
Since you are the onClickListener you can refer to this as the new onClickListener.
If you want only Red button is possible to click. You can set Enabled to false for all (exclude Red button). So, you will setOnClickListener to all button.
If all button possible to click, only run action when Red is clicked. You should check clicked button and compare if it is Red button in event Click
Remove OnClickListener from all button 'setOnClickListener(null)', and SetOnClickListener to Red
I would solve this a little bit differently.
Save the reference to button with red background redButton.
All buttons have the same onClick. In onClick just verify that clicked button is the one with red background (just check by reference). If not - do nothing. If yes: select new button, change background and save reference to new button.
Your onClick method should looks like this:
public void onClick(View view) {
if (view == redButton) {
redButton.setBackgroundColor(Color.WHITE);
Random r = new Random();
int oddValue_new = r.nextInt(4 - 0);
redButton = buttons[oddValue_new];
redButton.setBackgroundColor(Color.RED);
}
}
UPDATE
As #Mr Phuc 87 suggested you can use enabled. I think it is very good approach. In addition to enabled you can use state-list. Create state-list which have white background for android:state_enabled=false and red background for android:state_enabled=true. Now all you need is just change enabled property of your buttons.
OnClick should looks like:
public void onClick(View view) {
redButton.setEnabled(false);
Random r = new Random();
int oddValue_new = r.nextInt(4 - 0);
redButton = buttons[oddValue_new];
redButton.setEnabled(true);
}
state-list should looks like(put it in drawable):
<selector xmlns:android="http://schemas.android.com/apk/res/android"
<item android:state_selected="false" android:drawable=#color/white />
<item android:state_selected="true" android:drawable=red_here />
</selector>
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.
I am working on android.And i was creating an application in which i dynamically created a group of buttons on a button click.But what happens is buttons are created every time i click the button.i want this to happen once.Can i clear the space just at the beginning of OnClickListener()? i dunno how to do it.Below is my code.
button_generate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//*-----------clearing the variables--------*
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
int k=0,i=0,j=0;
count=3;
System.out.println("count is"+count);
while(j<count)
{
TableRow tr = new TableRow(EspeakerActivity.this);
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
rel.addView(tr);
}
j++;
}
}
}
);//*--------closing the button click------*
Give the buttons ID's and then use findViewByID() to see if the buttons already exist before adding them.
TableRow tr = new TableRow(EspeakerActivity.this);
tr.setId(/*some id*/)
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
//check rel already has that tr.. if it has don't add anythin.. better if you do it before even creating the TAbleRow
rel.addView(tr);
Hiding linear layout on runtime in Android
you can refer the link and i am sure you will get your ans.if not solve through this link
then tell me.
You can clear your TableLayout on each button click as follows
....
onClick(View v) {
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
for(int x=0; x<rel.getChildCount(); x++)
{
View v = rel.getChildAt(x);
rel.removeView(v);
}
....
}
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);
}
}