I want way to disable the Home Button & Back Button when a checkbox is checked in my application. I am on version 4.2.2. Here is my code, it does not work, the application stops when the box gets checked:
public void HardButtonOnClick(View v)
{
boolean checked1 = ((CheckBox) v).isChecked();
if(checked1)
{
SQLiteDatabase db;
db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
ContentValues values = new ContentValues();
values.put("hardBtn", "YES");
db.update("Setting", values, "id = ?", new String[] { "1" });
Toast.makeText(this, "Hard Button Locked", Toast.LENGTH_LONG).show();
//SharedPreferences pref = getSharedPreferences("pref",0);
//SharedPreferences.Editor edit = pref.edit();
//edit.putString("hard","yes");
//edit.commit();
/* String Lock="yes" ;
Bundle bundle = new Bundle();
bundle.putString("key", Lock);
Intent a = new Intent(Change_setting.this, ChildMode.class);
a.putExtras(bundle);
startActivity(a);*/
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
isLock = true;
}
else
{
SQLiteDatabase db;
db = openOrCreateDatabase("Saftey.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
ContentValues values = new ContentValues();
values.put("hardBtn", "NO");
db.update("Setting", values, "id = ?", new String[] { "1" });
//SharedPreferences pref = getSharedPreferences("pref",0);
//SharedPreferences.Editor edit = pref.edit();
//edit.putString("hard","no");
//edit.commit();
Toast.makeText(this, "Hard Button Un-Locked", Toast.LENGTH_LONG).show();
isLock = false;
}
}
How can I make this work? I do not want to hide the buttons, I only want them to not respond to clicks when the checkbox is checked.
You can override the back key onBackPressed() and let it do nothing, but you can't override the home button but you can add some code to onStop() which is called upon home key press.
here is a piece of code to control backpress
#Override
public void onBackPressed()
{
if ( checked1 ) // if checked do nothing , remeber tomove checked1 to be a class member
return;
super.onBackPressed();
}
#Override
public void onBackPressed() {
}
With this you override back button. Just do nothing in it.
This you can use if you do something special when u press back:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int vfBackId = viewFlipper.getDisplayedChild();
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
// Do some stuff
}
return false;
}
But you cannot override the home button. It's not provided from the Android system to handle the home button.
you cant disable home button in your application but you can disable back button with override
onBackPressed() and do nothing in that
You cannot disable home button.
There is no way to intercept the home button on Android, unless you make your app the home screen. This is for security reasons, so that malicious apps cannot take over your device by overriding all the buttons that can exit.
Home button is one sure short way to navigate to home screen.
If you want to handle the HOME button, implement a home screen.
Not able disable Home button on specific android devices
//Back key event detect
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// Quit if back is pressed
if (keyCode == KeyEvent.KEYCODE_BACK)
{
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Related
I wanted to add a `toast message` when clicked on a button and I added it. Now I want show it only **one time**, that means the toast message will **not show again** if clicked on the button after the first time **also after a restart of app**.
Please help me!
You can do it with SharedPreferences that you store in another class like Utility.java:
public class Utility {
public static SharedPreferences preferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static Boolean hasSendToast(Context context) {
return preferences(context).getBoolean("Toast", false);
}
public static void setSendToast(Context context, Boolean bool) {
preferences(context).edit()
.putBoolean("Toast", bool).apply();
}
}
And use it with your Toast inside the onClickListener in your MainActivity.java like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
if (!Utility.hasSendToast(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "My Toast", Toast.LENGTH_SHORT)
.show();
Utility.setSendToast(getApplicationContext(), true);
}
});
}
}
You might want to look into https://developer.android.com/training/data-storage/shared-preferences. After the first click write a boolean into shared preferences to indicate the first click has happened. Next time the user clicks the button make sure to check if that boolean has been set and don't show the toast if that's the case.
You can use a boolean flag and store the value using Shared Preference.
btn.onClickListener {
if(!getToastShownStatusFromSharedPreference()) {
showToast()
changeToastShowsStatusToSharedPreference()
}
/* other operations */
}
Yes you can do that with SharedPreferences which is a pref manager in android. You can follow the below process:
Declare a boolean as like isFirstTime = true.
On the click of the button check boolean status, and if its true then fire the toast message and make isFirstTime = false.
That's it.
I'm working on a project to make calculations. So, I have my EditText box working, and I want to hide the softkeyboard if the user clicks the DONE (or any other kind of button, GO, NEXT, etc.) and the EditText box is empty
Like so:
EditText is empty -> user clicks button -> softkeyboard hides
I have this piece of code that I manage to write using tutorials and guides over the internet
I do know it is to manage the listener of the button in the softkeyboard
TextView.OnEditorActionListener mEditor = new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if (actionId == EditorInfo.IME_ACTION_DONE)
{
//Calculations method
}
return false;
}
};
So, my question is: How can I manage the listener when the EditText is empty and not get errors?
you can use, for example:
TextView.OnEditorActionListener mEditor = new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if (actionId == EditorInfo.IME_ACTION_DONE)
{
if (!TextUtils.isEmpty(v.getText().toString())){
// you calculations method
} else {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return false;
}
};
I have two layouts, A and B. The app launches the A_layout, and through a button you can go to the B_layout. On default when you press the back button the app closes, doesnt matter if the app is on the A or B layout. When I override the back button to set the content view always on the layout A whenever the back button is pressed, then I cant open the B activity anymore through the button. How do I need to override the method correctly? :)
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
setContentView(R.layout.activity_main);
return true;
}
return super.onKeyDown(keyCode, event);
}
activity_main = A layout
Do I need to make Intents there?
You can override the onBackPressed function:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
finish();
}
When finsihing the activity is destroyed
What I'm trying to do is have a setting menu pull up when a button is pressed on my main menu (settings menu is implemented as a separate activity from my main). For simplicity's sake, assume that my main menu is blank except for 1 button that pulls up the settings menu. In the setting menu, there is one check box and one button "Done" that returns to the main activity.
How do I save a CheckBox's and load it (what should the code be, where should I put it, why, etc) ? I've tried googling it, and trying to replicate the results, but I can't seem to get it. 2 things have happened so far: nothing has saved, or my program crashes.
Once I have the information about the checkbox saved, how am I able to access this information from my main activity #I want to be able to run certain code based on if the user checked the box or not?
some results that I've landed on and tried:
How to save the checkbox state? - android
Saving Checkbox states
(Please keep in mind that I'm completely new to this)
public class Settings extends ActionBarActivity {
private static final String SETTING_CHECK_BOX = "SETTINGS";
private CheckBox cb;
//char boxChecked = '0';
#Override
protected void onCreate(Bundle savedSettings) {
super.onCreate(savedSettings);
cb = (CheckBox) findViewById(R.id.checkBox);
setContentView(R.layout.activity_settings);
cb.setChecked(isCheckedSettingEnabled());
}
private void setCheckedSettingEnabled(boolean enabled) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(SETTING_CHECK_BOX, enabled).apply();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
private boolean isCheckedSettingEnabled() {
return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(SETTING_CHECK_BOX, false);
}
public void onPause() {
super.onPause();
// Persist the setting. Could also do this with an OnCheckedChangeListener.
setCheckedSettingEnabled(cb.isChecked());
}
public void clickedDone (View v) {
SharedPreferences settings = getSharedPreferences("SETTINGS", 0);
settings.edit().putBoolean("check",true).commit();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So now my app doesn't crash anymore, but the state is not remembered (always unchecked when settings menu is open). I changed cb.setChecked(checkState) to cb.setChecked(TRUE), which didn't change anything (still always unchecked when settings menu is open). What is going on?
onSaveInstanceState() is only for persisting data for that instance of the Activity. Once that Activity has had finish() invoked, that state is no longer relevant. You need to write your settings to persistent storage. A simple storage solution for your case is SharedPreferences.
public class Settings extends ActionBarActivity {
// Create a constant for the setting that you're saving
private static final String SETTING_CHECK_BOX = "checkbox_setting";
private CheckBox mCheckBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mCheckBox = (CheckBox) findViewById(R.id.checkBox);
// Set the initial state of the check box based on saved value
mCheckBox.setChecked(isCheckedSettingEnabled());
}
#Override
public void onPause() {
super.onPause();
// Persist the setting. Could also do this with an OnCheckedChangeListener.
setCheckedSettingEnabled(mCheckBox.isChecked());
}
/**
* Returns true if the setting has been saved as enabled,
* false by default
*/
private boolean isCheckedSettingEnabled() {
return PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(SETTING_CHECK_BOX, false);
}
/**
* Persists the new state of the setting
*
* #param enabled the new state for the setting
*/
private void setCheckedSettingEnabled(boolean enabled) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean(SETTING_CHECK_BOX, enabled)
.apply();
}
}
Once the state data is stored using onSaveInstanceState(), the system uses onRestoreInstanceState(Bundle savedInstanceState) to recreate the state.
If you are using onSaveInstanceState() You have to override the function onRestoreInstanceState() in the activity or use the saved state in onCreate(). I think it's better to use onRestoreInstanceState() , which can reduce the code in onCreate(), because the onSavedInstanceSate() is called only when the system
closes the app to make room for new applications to run. If you just want to save the checked state , use shared preference, no need of onSaveInstanceState().
//decalre in class
private CheckBox cb;
private SharedPreferences preferences ;
private SharedPreferences.Editor editor;
private boolean CHECKED_STATE;
#Override
protected void onCreate(Bundle savedSettings) {
super.onCreate(savedSettings);
setContentView(R.layout.activity_settings);
preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
editor = preferences.edit();
CHECKED_STATE = preferences.getBoolean("check", false);
cb = (CheckBox) findViewById(R.id.checkBox);
cb.setChecked(CHECKED_STATE);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
editor.putBoolean("check", isChecked);
editor.commit();
}
});
}
this code saves the state on clicking the check box.
To make it save the state on Back Press , add the following to your activity.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
editor.putBoolean("check", cb.isChecked());
editor.commit();
}
for more details on Save instance state please refer this link.
Pretty simple; The dialog is showing. I press the back button on the phone, nothing happens. I've tried this, but it never gets called:
static void ProgressDialog(Context context)
{
String text = context.getString(R.string.dialog_loading_video);
vDialog = new ProgressDialog(context)
{
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// Nothing happening here!
}
return super.onKeyDown(keyCode, event);
}
};
vDialog = ProgressDialog.show(context, "", text);
vDialog.getWindow().setGravity(Gravity.TOP);
}
First, get rid of the second assignment to vDialog. Then, you need to make your dialog cancelable by calling setCancelable(boolean).
In line vDialog = ProgressDialog.show(context, "", text); you create new Dialog that doesn't have overriden onKeyDown() method. Replace this line with these code:
vDialog.setTitle("");
vDialog.setMessage(text);
vDoalog.show();