How to check if a button is clicked or not? - android

I have a Activity in android that has 4 buttons.
The first 3 buttons fetches a json data from a weather API for 1 day, next 5 days and next 10 days respectively.
I have a 4th button placed at the bottom of the screen, which takes user to second activity.
I want to restrict the entry of user to second Activity if no button from top 3 is clicked.
If the data is fetched, I mean any one of the top 3 buttons have been clicked, allow him to go to second activity on 4th button click else show a message.
How can i check on click of 4th button if any of the top 3 buttons have been clicked before?
Thanks

Put a boolean field in your activity, name it clicked and set it to false on the onCreate method of your first activity, then in the onClick method of your 3 buttons, set it to true,
and in the onClick method of your 4th button check it, if it's true go startActivity, else launch a Toast

You can make the 4th button look disable in "OnCreate" with the function "setEnabled"(may be wrong),
and then just set "setOnClickListener" for the 4th button when you click any of the others.
ps.
Can provide code example if needed.

Why don't you use if statement? You can keep the clicked count data under the first three buttons. Like this;
import java.util.stream.*;
int[] btnMemory = new int[4];
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnMemory[0] = 1;
// your code
}
});
after, you can check it with if statement under 4th button;
button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int sum = IntStream.of(btnMemory).sum();
if(sum >= 3)
// your code
}
});

Related

How to check if button has been clicked

I have a bunch of dynamic buttons which I am setting an onClickListeners as they are produced, as well as tagging them with IDs.
Not sure if this a simple one which I have just spent too much time staring at but this is the problem.
If a user clicks a button, it changes colour this is simple and has been achieved by:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (counter == 0) {
button.setBackgroundColor(Color.parseColor("#FF4DCBBF"));
Toast.makeText(getActivity(), "User Has Been Marked As Present",Toast.LENGTH_LONG).show();
//change boolean value
userPresent = true;
counter++;
} else {
button.setBackgroundColor(Color.parseColor("#FFFFFF"));
Toast.makeText(getActivity(), "User Has Been Marked As Absent",Toast.LENGTH_LONG).show();
//change boolean value
userPresent = false;
counter = 0;
}
}
});
If the user clicks it again, it will change back to the previous colour - but...
If the user clicks one of the other dynamic buttons that hasn't been previously clicked, the counter is thrown out.
I need to know if the button has been clicked and if not, should mark the user as present.
Currently, If on one button I click it and mark the user as present, and then move onto the next button, I will have to click it once (which marks the user as absent due to the counter) then press it again to mark the user as present.
I need the counter to treat each button individually, any ideas how this could be achieved?
Once the user has been marked present,maybe disable the onClick listener for that button since you wouldn't need it anymore?
I don't mean to sound condescending but I'm having trouble understanding what you're trying to achieve, but if each button is supposed to hold different information about a user, why not make a custom button that does just that? Make a class called customButton in your package and paste the following code there:
import android.content.Context;
import android.widget.Button;
public class customButton extends Button {
boolean haveIBeenClicked; //false by default
public customButton(Context context) {
super(context);
}
public void toggleHaveIBeenClicked(){
haveIBeenClicked=!haveIBeenClicked;
updateBackgroundColor();
}
void updateBackgroundColor(){
if (haveIBeenClicked){
this.setBackgroundColor(Color.parseColor("#FF4DCBBF"));
}
else{
this.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}
}
then, inside the onClick method (in the activity whose snippet you've shown earlier) you can just call
((customButton)v).toggleHaveIBeenClicked();
...after having created a customButton object and setting an on click listener on it.
Please let me know if this achieves what you desired. If you have trouble running this code, make sure to let me know if the comments and we'll work it out

How to change button color by clicking another button from another activity permanently

i have a problem
i have button A in first activity and button B in second activity,i want when someone click button B in second activity then color of A button is change permanently it never reverse to previous colour again when ever user not uninstall the app
This is not how you ask a question in SO, you should try something first and when you hit a problem, then you can ask your question as specific you can, along with all things you have done. you can read about how you can ask a good question in here.
Now you can try something like this:
//create a method in your first activity, (where the button color should change):
public void changeColorInFirstActivity(){
Button btnA = (Button) findViewById(R.id.myButtonA);
btnA.setBackgroundColor(getResources().getColor(R.color.red));
}
And add this in your second activity where you want to click on a button to change the first activity button color:
Button btnB = (Button) findViewById(R.id.myButtonB);
btnB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity secondActivity = new FirstActivity();
firstActivity.changeColorInFirstActivity();
}
});
Now after setting the color, save the color int in shared preferences and set the value you get on your button color in your First activity

100 Buttons and only 1 Active

I have one activity and here i have 100 buttons, i want that when i press Button 1 then press another Button the Button 1 should get unpressed.
i know i can make this with
if(Button1.isPressed()) {
Button2.setPressed(false);
Button3.setPressed(false);
Button4.setPressed(false);
Button5.setPressed(false);
Button6.setPressed(false);
Button7.setPressed(false);
Button8.setPressed(false);
......................... }
else { do nothing }
.... BUT!
it's too much code
Coders will kill me or will just laugh on me.
any ideas?
maybe there is a way to unpress the all buttons from the activity?
Not the prettiest solution ever, but you could make an OnClickListener like this:
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
ViewGroup parent = (ViewGroup) v.getParent();
for (int i = 0; i < parent.getChildCount(); i++) {
View current = parent.getChildAt(i);
if (current != v && current instanceof Button) {
((Button) current).setPressed(false);
}
}
((Button) v).setPressed(true);
}
}
and attach it to all of your buttons.
Then, whenever a button is clicked, it will iterate over all views that are in the same layout (or actually, view group) as the clicked button, and, for any of those views that are buttons except for the clicked button, it will call setPressed(false).
Note that this only works out of the box if all the buttons are in the same layout. If they are in nested layouts, you will have to adapt it a little.
Off topic: What do you need 100 buttons for? That's a lot of buttons. You may want to redesign your user interface
Ok so instead of looping through all the buttons on over and over again when one button is pressed, you can just store a variable which stores the button number of the button that was last pressed. Now, when the second button is pressed, disable the button that was pressed earlier, you get its index from the saved variable, enable the button that was pressed and store its index in the variable.
Heres an example pseudo code to give you and idea:
int buttonLastPressed = 0;
void onButtonClick(Button buttonPressed){
if(buttonLastPressed != 0){
disableButton(buttonLastPressed);
enableButton(buttonPressed);
buttonLastPressed = buttonPressed.getIndex()
}
}
Saves you from looping through each and every button to disable it.
Define id of button 1 to 100
When press button occurs save it's id in some member variable like previous_pressed
Before updating a previous_pressed value find and unpress previous pressed button like this
Button previous_pressed_button = (Button) findViewById(previous_pressed);
Now you have the previous pressed button, So upress it or whatever.

TableLayout, Different Button actions depending on data in TableRow

I have the following problem:
I have a TableLayout along with several TableRows, which are dynamically created.
On the right side of every row I create a button, which should call another activity.
Now I want to pass some information with intent.putExtra(). In this case I want so pass the row number, which is also the first information in the row.
Here is a picture of the current state:
This is how I create the buttons during run-time (in a loop):
Button b1 = new Button (this, null, android.R.attr.buttonStyleSmall);
b1.setId(1000+grButtonId);
b1.setText("Request GR");
b1.setLayoutParams(params);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Some code, taken out for clarity
// See next code snippet
}
});
grButtonId++;
tr.addView(b1);
My idea so far is to use the id of the button (of course), and get the line number by the value of grButtonId.
Now comes my problem, let's have a detailed look at my onClickmethod:
#Override
public void onClick(View view) {
// finished is true, as soon as GRRequest has recieved the data
if(!finished & !dataRequested){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
dataRequested=true;
}
else{
if (dataRequested){
b1.setText("Show GR");
}
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
When I request my data, the button I clicked on gets set to "Show GR" , as intended. The other buttons stay on "Request GR", this is also fine. But now I want these Buttons to Change to "Show GR" when tapped first and on second tap start the activity.
By now, the buttons change to "Show GR" and directly start the activity.
What would be a solution, to make this work?
Create a boolean Array clickedOnce[] = new boolean[grButtonId+1] one field for every Button.
Then have this
public void onClick(View view) {
if(!finished){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true; //sets the clickedOnce for this button to true, substring(1,4) is needed to cancle the leading 1 from the id
}
else{
//Checks, if the button was clicked once
if (!clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]){
b1.setText("Show GR");
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true;
}
else{
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
}

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.

Categories

Resources