This is code of button:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.setEnabled(true);
}
},120000);
}
});
I know that i need to create a sharedpreferences, but I didn't understand how to save condition of button which have a timer, because i know how to save without ussing handler.
How can i do this?
You'll have to use shared preference to save the state. Then, while creating the view of you fragment or activity, you should check the value you saved with shared preference and set the button state accordingly.
Permit me, please, to answer in Kotlin, maybe you or your IDE can do the translation.
To save your button state to shared preference, define this function;
fun setButtonState(context: Context, buttonEnabled: Boolean) {
PreferenceManager.getDefaultSharedPreference(context).edit()
.putBoolean("button", buttonEnabled).apply()
}
Then to get your saved button state from shared preference, define this function;
fun getButtonState(context: Context): Boolean {
return PreferenceManager.getDefaultSharedPreference(context)
.getBoolean("button", false)
}
In your onCreateView set the button state in accordance to your saved value.
val buttonEnabled = getButtonState(requireContext())
button = view.findViewById(R.id.button)
button.isEnabled = buttonEnabled
Then toggle the saved state in shared preference like so:
button.setOnClickListener {
button.isEnabled = false
setButtonState(requireContext(), false)
Handler(Looper.getMainLooper()).postDelayed({
button.isEnabled = true
setButtonState(requireContext(), true)
}, 120000)
}
I hope this helps. :)
Related
I have a button like a switch where I am trying to setClickable(false) after I click it so that only the first click will be handled
(additional clicks are ignored in the case of accidental double-clicks/multiple-clicks).
Here is a similar code:
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button.setClickable(false);
//do other things
}
});
Then eventually, I have a code somewhere where I will reset the clickable to true, depending on a state variable, so I can switch-off.
The problem is when I click the button very quickly, it seems the succeeding clicks are still handled.
Is there a delay to the effects of setClickable()?
Also, I have read about using setEnabled(false) instead, but I cannot use it in my case. I need the button to still be enabled but not clickable.
Judging from your comment you probably need something like this.
Boolean SWITCH_ON = false;
Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(!SWITCH_ON ){
SWITCH_ON = true;
}
}
});
Button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if(SWITCH_ON ){
// do your task for long click here ...SWITCH_ON
}
return true;
}
});
You can use button.setEnabled(false); within your onClick method to disable the button.
Disabled buttons don't trigger the onClick method, and you can easily re-enable it with button.setEnabled(true); when needed.
You could add another variable named buttonEnabled or so and initialize it with true. Then in the onclick do this:
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button.setClickable(false);
if(buttonEnabled) {
//do other things
}
buttonEnabled = false;
}
});
Note that you need to change the variable to if you want to reactivate it
I have 6 options that the user can select from and a button that takes them to the next page when clicked. I have two pages like this. After one choice from each page is selected, I would like to display certain text depending on the radio buttons clicked previously, in another activity. How can I do this in java in android studio?
If you are controlling the FragmentManager you can just pass the options as an argument to the next Fragment's constructor otherwise, you can save everything in a static variable (as long as no Views are in there, so don't store the radio buttons there) and access that variable from outside.
Like this:
public class MyFragment {
public static boolean isRadioButtonXPressed = false; //change to true if it's pressed by default
public void onCreate(...) {
radioButtonX.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
isRadioButtonXPressed = checked;
}
});
}
}
//from the other fragment
public class MyFragment2 {
public void onCreateView(...) {
if (MyFragment.isRadioButtonXPressed) {
//it's been pressed
} else {
//it's not been pressed
}
}
}
There are many different ways.
As you are using activity, you can use Intent to pass data. Here is a sample:
Intent page = new Intent(FirstActivity.this, SecondActivity.class);
page.putExtra("key", "This is my text");
startActivity(page);
For getting the value on Second Activity onCreate() method:
String value = getIntent().getStringExtra("key");
I have successfully implemented a custom Dialog box that appears when the user tries to leave an activity via a back button or by using onBackPressed(). They can simply cancel the dialog box or continue, and leave the activity. This function has been implemented in multiple activities, however its making my code a lot longer than it needs to be. I wanted to know how to create a util that can be referenced in different activities, without the need for the chunk of code to copy pasted multiple times. Please note that I am retrieving the dialog title and description from string.xml
This is my code:
Dialog customDialog;
Button button_one, button_two;
TextView dialog_title, dialog_description;
customDialog = new Dialog(this);
//Back button will close app
#Override
public void onBackPressed() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description); dialog_description.setText(getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
UPDATE
Created a Java file called "DialogBoxMessage"
DialogBoxMessage Code:
class DialogBoxMessage {
private Dialog customDialog;
private TextView dialog_title, dialog_description;
private Button button_one, button_two;
//Custom Dialog Box Initialization
DialogBoxMessage(Button myButtonOne, TextView myDialogTitle, TextView myDialogDescription, Dialog myCustomDialog) {
customDialog = myCustomDialog;
button_one = myButtonOne;
button_two = myButtonOne;
dialog_title = myDialogTitle;
dialog_description = myDialogDescription;
}
void leaveActivity() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description);
dialog_description.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(Resources.getSystem().getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(Resources.getSystem().getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
}
I input the following code in another activity
Other activity code:
//Reusable exit dialog message
DialogBoxMessage dialogBoxMessage;
//Back button will close app
#Override
public void onBackPressed() {
dialogBoxMessage.leaveActivity();
finish();
}
But it doesn't seem to work, I think there are a lot of issues... please help :(
I assume customDialog is a seperate class you wrote - therefore i would suggest you put main information like contentview, title, message or type in the constructor when you initialize ur Dialog.
For your onClick Method I suggest you create an Interface to handle Button Clicks in your
customDialog class.
This could be implemented as a static method in a utilities class. The method would require 'this' as a parameter, which contains the activity context. The method should return the result of the button press. The activity can use this response to determine if finish() should be called or not.
UPDATE
I had suggested a simple static method, but you've gone down the object-oriented route. That's fine.
However, your constructor requires passing in several views, which wouldn't appear to achieve the code efficiency you are after.
Your constructor should just require the Activity context; everything else is encapsulated in your new class.
In each Activity's onBackPressed method you will need to create the object with
dialogBoxMessage = new DialogBoxMessage(this);
before you can call any of that object's methods.
I have a fragment with a button that sets a background theme for the whole app. I have set up an interface so the fragment can tell the main activity to set the background or remove it depending on what button the user clicks.
The problem is that every time the app is opened the background isn't saved and needs to be toggled again. I have seen that this can be solved with SharedPreferences but implementing it here is confusing me
In my fragment This presents two buttons that send the values 1 or 2 to the main activity to toggle the background
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
In my Main Activity This takes the value from the listener and toggles the background depending on what the value is
#Override
public void themechanged(int value) {
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value!=2||value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
}
Use SharedPrefence to store the value for theme like-:
Global Variable
SharedPreferences pref;
SharedPreferences.Editor editor;
In OnCreateView()
pref = getActivity().getSharedPreferences("Theme", Context.MODE_PRIVATE);
editor = pref.edit();
Now, store preferences on Button click
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 2);
editor.commit();
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 1);
editor.commit();
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
and then, In OnCreate() of MainActivity you can check like
SharedPreferences pref = getSharedPreferences("Theme", MODE_PRIVATE);
value= pref.getInt("yourTheme", 1);//1 is default value
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
Done, it may be helpful
In the onClick() you should do 2 things:
Sent the value to the listener (you're already doing this)
Save this value to the preferences (already posted how to do that here)
Then, in the onCreate() of your MainActivity you should check for that preference and do the same you are doing on themechanged(int)
Actually, you could use only one onClickListener(), this way:
// Not need to cast to `Button`, since all views can have an onClickListener
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
// Put this as a member of your Fragment class.
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.enable) {
// Save your preference here
// ...
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
if (v.getId() == R.id.R.id.disable) {
// Save your preference here
// ...
listener.themechanged(2);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
}
Let me share this more complex example which can cover this and future needs: https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111
The PersistenceManager class is generic, all your app data should be included in the Settings class.
I hope it helps.
Sorry for my bad english.
I have 2 classes,
1 MainActivity.java (Standard)
2 settings.java (for settings)
I have a RadioGroup with 5 Radiobuttons.
I save the state of the radio buttons as follows (in to settings.java class):
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("status", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("blue", blue.isChecked());
editor.putBoolean("orange", orange.isChecked());
editor.putBoolean("purple", purple.isChecked());
editor.putBoolean("grey", grey.isChecked());
editor.putBoolean("green", green.isChecked());
editor.commit();
}
public void loadSettings () {
SharedPreferences settings = getSharedPreferences("status", 0);
royalBlue.setChecked(settings.getBoolean("blue", false));
orange.setChecked(settings.getBoolean("orange", false));
purple.setChecked(settings.getBoolean("purple", false));
titan.setChecked(settings.getBoolean("grey", false));
eighties.setChecked(settings.getBoolean("green", false));
}
the status of the radio buttons is saved successfully. Even after a restart of the app the radio button is saved.
I would like now when the RadioButton orange (or other) is selected, the ImageButton will change my image. I would like to make in the MainActivity.
I have tried it in the Main Activity so but I always get a NullPoinException:
Code from the Main ...
private settings load = new settings();
...
...
public void change (){
if (load.orange.isChecked()){
imBuOn.setImageResource(R.drawable.orange);
}
as I said I can so unfortunately unable to access the status of the radio button.
Do I need to maybe use PreferenceManager? how shall I put it best?
You don't need to create an instance of the settings class and fetch the value of the checkBox. Instead, you should just use the same code as given in the loadSettings method since you are just accessing the SharedPreferences file.
So, in your MainActivity, just run this
private void checkAndSetImage()
{
SharedPreferences settings = getSharedPreferences("status", 0);
if(settings.getBoolean("orange", false))
{
imBuOn.setImageResource(R.drawable.orange);
}
}
Just call this function to wherever applicable.