How to check if button has been clicked - android

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

Related

Listening for clicks on a disabled AlertDialog-Button

I want to listen for clicks on the positive button of an AlertDialog, which I have disabled by calling button.setEnabled(false);.
How should I do this? If this is not possible, is there a known workaround?
PS. The reason I want to do this, is that I want to show a toast when somebody hits the button, saying "You need to do this before you can continue".
This is not a way to listen for clicks on a disabled button. This is a workaround.
I liked the result I got by changing the color of the button, making it look like it's disabled.
What you want to do:
// Instantiate positive button
final Button posButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
// Save the original button's background
final Drawable bg = posButton.getBackground();
// Set button's looks based on boolean
if (buttonDisabled) {
posButton.setTextColor(getResources().getColor(R.color.disabledButtonColor, null));
// R.color.disabledButtonColor == #DBDBDB, which is pretty close to
// the color a disabled button gets.
posButton.setBackgroundColor(Color.TRANSPARENT);
// Color.TRANSPARENT makes sure all effects the button usually shows disappear.
} else {
posButton.setTextColor(getResources().getColor(R.color.colorPrimaryDark, null));
// R.color.colorPrimaryDark is the color that gets used all around my app.
// It was the closest to the original for me.
posButton.setBackground(bg);
// bg is the background we got from the original button before.
// Setting it here also re-instates the effects the button should have.
}
Now, don't forget to catch your buttons actions whenever it's "disabled"
public void onClick(View v) {
if (buttonDisabled) {
// Button is clicked while it's disabled
} else {
// Button is clicked while it's enabled, like normal
}
}
That should do, have fun with it.

Dynamic Buttons with two functionalities ANDROID

I have dynamic buttons that are created by a variable that can change.I want that these buttons have two functions. I did one option but I don't know how to implement the other option.
the first time I click the button I call a function that do something and the second time that I click the same button I would like to do another action. And I want to repeat this running with all the dynamic buttons created.
My code is:
LinearLayout buttonsLayout = (LinearLayout)findViewById(R.id.linearlayoutUp);
for(int i=0;i<drawView.getNumeroMallas();i++){
Button buttonMalla = new Button(this);
buttonMalla.setText("Malla "+(i+1));
buttonMalla.setId(i+1);
final int index = i;
buttonMalla.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Malla malla = drawView.getMalla(index);
drawView.paintMallaSelected(malla);
}
}
});
buttonsLayout.addView(buttonMalla);
}
}
EDIT - Very important:
I readed your code again, you could use the getTag/setTag to remember the last state of the button (i missed the for part, sorry!)
for(int i=0;i<drawView.getNumeroMallas();i++){
Button buttonMalla = new Button(this);
buttonMalla.setText("Malla "+(i+1));
buttonMalla.setId(i+1);
buttonMaila.setTag(Boolean.FALSE);
Then in setOnClickListener
if (((Boolean)v.getTag()) == Boolean.TRUE)
{
// Do first action
v.setTag(Boolean.FALSE);
}
else
{
// Do second action
v.setTag(Boolean.TRUE);
}
An idea could be to use a variable to know which was the last action.
A boolean variable
private boolean action = false;
If action is false do the first thing and set it to true. If it's true do the second action and set it to false.
It should go out any method (global of the class)
Something like
private boolean action;
buttonMalla.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (action == true)
{
// Do first action
}
else
{
// Do second action
}
action = !action;
Malla malla = drawView.getMalla(index);
drawView.paintMallaSelected(malla);
}
}
});
Anyway if it does something of important you should manage better the button (example button action is not based on a boolean variable but in a specific state.) time ago i builded a "select all" and "unselect all" function in an app and i checked if the user have unselect manually something to let the button act again like a "select".. I hope i gave to you an idea.
Anyway the boolean variable is the most immediate way to do it.

Change Text in a same Layout

I'm Making simple app for project
That App contains lot of text so i want,
"when a button is pressed, text should Change in same layout"
like PowerPoint slide.
I want change text only not scroll.
Now i made my app, have lots of Windows or Layouts.
It is not looking good, too much layout in simple app so please help me .
Thanks in advance
Doing this is very easy, I will quickly walk you through the Algorithm:
Set a class level variable called as FLAG initialize it to 1.
Let us assume that FLAG = 1 will represent the first slide. FLAG = 2 the second slide and so on.
Now in your button click you can use a switch case or an if else condition, based on the value of the flag display the relevant text in textview.
Once done, increment the flag, for the next set of sentence(s).
Class level:
int FLAG = 1;
onCreate:
Initialize your textView:
TextView mtv = (TextView)findViewById(R.id.yourid);
Set a button click listener:
private View.OnClickListener slides = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(FLAG ==1)
mtv.setText("First slide");
else if(FLAG ==2)
mtv.setText("Second Slide");
//and so on...
FLAG = FLAG+1;//increment flag
}
};

How to check if a button is clicked or not?

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

DialogPreference shouldn't close if no option selected

I have a DialogPreference and I want to avoid the user from closing it when pressing "OK", "Cancel", etc.
How should I do that?
EDIT:
I tried to reach the OK button to disable when the dialog is created. But I couldn't make it :(
The solution is quite easy. Overwrite showDialog and set your own click listener to the buttons you want to intercept.
#Override
protected void showDialog(Bundle bundle) {
super.showDialog(bundle);
Button pos = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
pos.setOnClickListener(...);
}
In your click listener you can do the validation you want.
A tweak could be to create a custom dialog where you define your own buttons (OK and Close).
public class YourClass implements OnClickListener {
private Button DialogButton;
private Dialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainLayout);
/* Your code... */
DialogButton = (Button) findViewById(R.id.DialogButtonId);
DialogButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.DialogButtonId:
LayoutInflater inflater = LayoutInflater.from(YourClass.this);
final View inflay = inflater.inflate(R.layout.DialogLayout, (ViewGroup) findViewById(R.id.RootIdOfDialogLayout));
TextView YourTextView = (TextView) inflay.findViewById(R.id.TextViewId);
Button cancel = (Button) inflay.findViewById(R.id.CancelButtonId);
cancel.setOnClickListener(YourClass.this);
Button ok = (Button) inflay.findViewById(R.id.OkButtonId);
ok.setOnClickListener(YourClass.this);
dialog = new Dialog(YourClass.this);
dialog.setContentView(inflay);
dialog.setTitle(getString(R.string.TitleStringId));
dialog.show();
break;
case R.id.CancelButtonId:
/* Checking if the user selected an option if true call dialog.dismiss() */
break;
case R.id.OkButtonId:
/* Here handle your preferences (e.g. putString(String key, String value)) */
/* Checking if the user selected an option if true call dialog.dismiss() */
break;
}
}
}
Check out http://developer.android.com/reference/android/content/SharedPreferences.Editor.html in order to handle your preference in onClick. I didn't test this code just wrote it to show you how you could solve it!
The dialog stays open until you call dialog.dismiss();. In that case you'll have to create your drop-down-menu, polls or what ever you want to display in your layout file. After pressing ok or cancel you should check if the user made a choice, and parse that choice into your preferences. (check link above)
Rgds
Layne
You could try opening it again.
Why would you want to prevent users to close the dialog? Users should be able to have 'full' control of their device.
You can see the source code of DialogPreferences here:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/preference/DialogPreference.java
And then, copy most of it to your code, modifying the code as needed.
How about overriding the onDismiss() method and implementing a canExit() method with the validations you want to occcur? E.g. :
public class MyDialogPref extends DialogPreference {
#override public void onDismiss(DialogInterface dialog) {
if (canExit()) {
super.onDismiss(dialog);
}
}
...
}
A good UI should have a default selection/option already selected (the previously user-entered options or a program default).
Presenting a dialog asking for a change in options without any indication of what you already have is bad UI design.
This way if the user clicks Cancel, nothing changes and they saw what the option selected was. If they make no change and click OK then nothing really changes either.
Software is supposed to make doing specific tasks easier, not force the user to process the apps logic themselves.

Categories

Resources