Random Button enabling in Android - android

I need to enable a button using a random number. The names of the buttons are button1, button2, button3. Here's my code:
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
b.setBackgroundColor(R.color.redwue);
setNextButton(b);
}
});
public void setNextButton(Button str){
System.out.println("&&&&&&&&&&& SETNEXTBUTTON");
str.setEnabled(false);
int zufall = (int) (Math.random()*2);
int buttonid = str.getId();
int buttonname = (int) str.getId();
System.out.println("&&&&&&&&&&&" + getResources().getResourceEntryName(buttonid));
Button bnew = new Button(this);
bnew.setTag(buttonname);
System.out.println("&&&&&&&&&&&" + getResources().getResourceEntryName(bnew.getId()));
bnew.setEnabled(true);
Now with this solution, I get an Unable to find resource id error. I know why that is but I can't find a solution for how to randomly enable a different button?

When a Button is created by Button bnew = new Button(this); no id is assigned to that Button. You must do it by yourself:
bnew.setId(yourId);
Create an array that save the id for all buttons you want to work. Match the randon number with the position on array to get the id for that button.
int[] buttonIds = {R.id.button1, R.id.button2, R.id.button3};
Button bnew = (Button) findViewById(buttonIds[zufall]);
bnew.setEnabled(true);
You must ensure zufall is in [0, buttonIds.length - 1] range

Related

Which Button was pressed first?

I need a way to know which of my buttons was pressed first. The app layout is more or less like this.:
Button1 Button2
Button3 Button4
Button5 Button6
Button7 Button8
Button9 Button10
Button11 Button12
And if one of the buttons of it's "line" is pressed, the other disappears. The thing is, I have no idea how to know which one of all these 12 buttons was pressed first, then pressed second, then pressed third and so on...
The code I have for hiding buttons works well, but that's pretty much the easy part.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
}
});
I searched but maybe I don't know what exactly to search for, and I didn't find a good answer.
You can do it like this:
1) Have a HashMap where you link both of your buttons on the same line to each other. 2) Have an ArrayList of button id's where you can hold the order of presses. 3) Implement a method which will perform the mapping and call it in your Activity's #onCreate method. 4) Set your global listener instance to all of your buttons.
private HashMap<Integer, Integer> buttonMap = new HashMap<>();
private ArrayList<Integer> buttonPressedOrder = new ArrayList<>();
// A global listener instance to be set to all of your buttons
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View selectedButton) {
int selectedButtonId = selectedButton.getId();
//Add pressed button to pressed buttons list
buttonPressedOrder.add(selectedButton.getId());
//Find button to hide and hide it
int hidingButtonId = buttonMap.get(selectedButtonId);
Button hidingButton = findViewById(hidingButtonId);
hidingButton.setVisibility(View.GONE);
}
}
//Put these inside your activity#onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mapButtons();
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
...
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
}
// A method for mapping your buttons in the same line to each other
private void mapButtons(){
buttonMap.put(R.id.button1, R.id.button2)
buttonMap.put(R.id.button2, R.id.button1)
buttonMap.put(R.id.button3, R.id.button4)
buttonMap.put(R.id.button4, R.id.button3)
...
}
Whenever you need to see in which order the buttons are pressed, use this method
public void getButtonPressedOrder(){
Resources res = getResources();
int numberOfPressedButtons = buttonPressedOrder.size();
for(int i=0; i<numberOfPressedButtons; i++){
Log.i("PressOrder", res.getResourceEntryName(buttonPressedOrder.get(i))
+ " is pressed at " + (i+1) + " order");
}
}
which will log something like:
I/PressOrder: button1 is pressed at 1 order
I/PressOrder: button5 is pressed at 2 order
I/PressOrder: button10 is pressed at 3 order
Hope this helps!

Android: How to set onClickListener to different button when clicked

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>

OnClickListener for Dynamically created buttons

I'm new to android Development and I hope you can help me.I created Buttons Dynamically ( Based on the contents of my Database). I also made onclicklistener for those buttons. The problem now is, If I click the buttons, Nothing happens. There is also no error shown in logcat. Why do you think this happened? Any response will be appreciated.
Here is my code on creating buttons:
final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
cursorCol = scoresDataBaseAdapter.queueCrit(mRowId);
for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
int Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("_id")));
Log.i("_id","_id : "+Id);
String CriteriaButton = cursorCol.getString(cursorCol.getColumnIndex("Criteria"));
Log.i("CriteriaButton","CriteriaButton : " + CriteriaButton);
Button btn = new Button(this);
btn.setText(" " + CriteriaButton + " ");
btn.setId(Id);
btn.setTextColor(Color.parseColor("#ffffff"));
btn.setTextSize(12);
btn.setPadding(10, 10, 10, 10);
btnlayout.addView(btn,params);
btn.setOnClickListener(getOnClickDoSomething(btn));}
Now after my OnCreate, I have the following method to set the onclicklistener
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
String criteria = button.getText().toString();
if ("Exams".equals(criteria)){
Toast.makeText(getApplicationContext(),"Exams Selected",2).show(); }
else if ("Quizzes".equals(criteria)){
Toast.makeText(getApplicationContext(),"Quizzes Selected",2).show(); }
}
};
}
Change
String criteria = button.getText().toString();
to
String criteria = button.getText().toString().trim();
Inside onClick method use View parameter of onClick method to get Text from pressed button as:
public void onClick(View v) {
Button button = (Button)v;
String selectedText = button.getText().toString();
....your code here
}

ImageButton Click Action Android

I've stored the imagebutton info in an xml. It's image path,width,height and so on.
But since there are multiple images I want to store data for each imagebutton while it's clicked. for example, if there are two buttons named male and female, i want to set String value = "male"; if male image button is clicked. But it did not work. Can somebody help me?
public void AddAllImageButtons() throws IOException {
AbsoluteLayout Layout = (AbsoluteLayout) findViewById(R.id.layout1);
ImageButton btn = new ImageButton(this);
Layout.addView(btn);
AbsoluteLayout.LayoutParams absParams = (AbsoluteLayout.LayoutParams) btn
.getLayoutParams();
absParams.x = x;
absParams.y = y;
btn.setLayoutParams(absParams);
btn.setBackgroundDrawable(null);
btn.setImageBitmap(BitmapFactory.decodeStream(getAssets().open(path)));
if(type.equals("imagebutton")){
if(elementId.equals("female")){
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gender = elementId;
GenerateAlertBoxes(gender);
}
});
}
Id is the image button id which is created in xml file.
AlertBox text does not show "female" for this example.
you can setTag("value") to set the value in the ImageButton btn and on the onclick event you can use getTag() function to retrieve the value and set it to gender.
use btn.setTag(elementid); whenever you add a btn to the layout.......
inside btn.setOnClickListener you can write v.getTag().toString() to get the value and set it to gender......
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gender = v.getTag().toString();
GenerateAlertBoxes(gender);
}
});

android get Colour

Hello i have lots of button with the same OnClickListener, the buttons have different colours, how can i get the colour(or the colour resource) of the pressed button ?
Here is the code i use
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener colorButtonListener = new View.OnClickListener(){
public void onClick (View v){
textarea_note.setBackgroundDrawable(v.getBackground());//set edit background the same of the button
dialog.dismiss();
}
};
Button button1 = (Button) dialog.findViewById(R.id.button1);
Button button2 = (Button) dialog.findViewById(R.id.button2);
Button button3 = (Button) dialog.findViewById(R.id.button3);
Button button4 = (Button) dialog.findViewById(R.id.button4);
Button button5 = (Button) dialog.findViewById(R.id.button5);
Button button6 = (Button) dialog.findViewById(R.id.button6);
Button button7 = (Button) dialog.findViewById(R.id.button7);
Button button8 = (Button) dialog.findViewById(R.id.button8);
Button button9 = (Button) dialog.findViewById(R.id.button9);
/*for changing the colour when the user clicks on a button*/
button1.setOnClickListener(colorButtonListener);
button2.setOnClickListener(colorButtonListener);
button3.setOnClickListener(colorButtonListener);
button4.setOnClickListener(colorButtonListener);
button5.setOnClickListener(colorButtonListener);
button6.setOnClickListener(colorButtonListener);
button7.setOnClickListener(colorButtonListener);
button8.setOnClickListener(colorButtonListener);
button9.setOnClickListener(colorButtonListener);
/**for the round corner*/
Resources res = this.getResources();
button1.setBackgroundDrawable(this.Sd(res.getColor(R.color.color1x1)));
button2.setBackgroundDrawable(this.Sd(res.getColor(R.color.color1x2)));
button3.setBackgroundDrawable(this.Sd(res.getColor(R.color.color1x3)));
button4.setBackgroundDrawable(this.Sd(res.getColor(R.color.color2x1)));
button5.setBackgroundDrawable(this.Sd(res.getColor(R.color.color2x2)));
button6.setBackgroundDrawable(this.Sd(res.getColor(R.color.color2x3)));
button7.setBackgroundDrawable(this.Sd(res.getColor(R.color.color3x1)));
button8.setBackgroundDrawable(this.Sd(res.getColor(R.color.color3x2)));
button9.setBackgroundDrawable(this.Sd(res.getColor(R.color.color3x3)));
//now that the dialog is set up, it's time to show it
dialog.show();
As far as i know, You can get the color values(for eg: R.color.green) but you can get a drawable object of the button.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Drawable d = v.getBackground()
}
});
I've found this method, but i have never try it :
int color = v.getSolidColor();
TextView txt = (TextView)findViewById(R.id.txtColor);
txt.setText("Color Of Button ");
View.OnClickListener colorButtonListener = new View.OnClickListener(){
public void onClick (View v){
txt.setTextColor(v.getSolidColor());
textarea_note.setBackgroundDrawable(v.getBackground());//set edit background the same of the button
dialog.dismiss();
Log.i("Color of Button","Color = "+v.getSolidColor() );
}
};
Note : follow this link : getSolidColor()
in your Code , try to replace the :
button1.setBackgroundDrawable(this.Sd(res.getColor(R.color.color1x1)));
with :
button1.setBackgroundRessource(R.color.color1x1);
download this project , i've created 4 buttons, and i get the color of the background ;) , enjoy it
Get Color of Buttons
Hope it helps

Categories

Resources