Toggle method not working properly in Android Studio using JAVA - java

I made simple dark/light mode switcher. The application OnCreate detects the mode you are on and than changes the boolean. I'm toggling this boolean and theme with button but for some reason it changes to false after second click. It only does that when the boolean is true. On false it works fine. Here's my code:
ImageButton dark_light;
boolean isDarkMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dark_light = findViewById(R.id.dark_light);
int nightModeFlags =
getApplicationContext().getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK;
switch (nightModeFlags) {
case Configuration.UI_MODE_NIGHT_YES:
dark_light.setImageResource(R.drawable.light);
isDarkMode = true;
break;
case Configuration.UI_MODE_NIGHT_NO:
dark_light.setImageResource(R.drawable.dark);
isDarkMode = false;
break;
}
dark_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isDarkMode) {
dark_light.setImageResource(R.drawable.light);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode = true;
} else {
dark_light.setImageResource(R.drawable.dark);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode = false;
}
Log.d("Dark_Light", String.valueOf(isDarkMode));
}
});
}

Whenever night mode is toggled, onCreate will be called again.
getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; always gives you the initial configuration so you are always writing the same value to isDarkMode whenever the night mode is toggled.
To get the current night mode configuration, use AppCompatDelegate.getDefaultNightMode() instead
int nightModeFlags = AppCompatDelegate.getDefaultNightMode();
switch (nightModeFlags) {
case AppCompatDelegate.MODE_NIGHT_YES:
dark_light.setImageResource(R.drawable.light);
isDarkMode = true;
break;
case AppCompatDelegate.MODE_NIGHT_NO:
dark_light.setImageResource(R.drawable.dark);
isDarkMode = false;
break;
}

Related

Unexpected Token And Cannot resolve constructor

I was creating Ontouchlistener But i got 2 error. 1st unexpected token and 2nd Cannot resolve constructor 'Intent(anonymous android.view.View.OnTouchListener, java.lang.Class<com.krish.galaxypdfviewer.Website>)'
And when i tried onclick listener it worked without any error but i want to use Ontouchlistener
Here is the code whats wrong here?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton actionButton = findViewById(R.id.action_button);
defineView();
handleIntent();
defineActionBar();
checkPermission();
long start;
actionButton.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(final View v, final MotionEvent event){
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
start=System.currentTimeMillis();
return true;
case MotionEvent.ACTION_UP:
if(System.currentTimeMillis()-start<500){ //Click is less than 500ms, you can adjust this value later...
//Do what you want on click over here...
}else{
openWebsite(); //It's a long click, do what you want over here...
}
return true;
default:
return false;
}
});
public void openWebsite() {
Intent intent = new Intent(this, Website.class);
startActivity(intent);
}
There's a missing closing curly brace for the onTouch method.
actionButton.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(final View v, final MotionEvent event){
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
start=System.currentTimeMillis();
return true;
case MotionEvent.ACTION_UP:
if(System.currentTimeMillis()-start<500){ //Click is less than 500ms, you can adjust this value later...
//Do what you want on click over here...
}else{
openWebsite(); //It's a long click, do what you want over here...
}
return true;
default:
return false;
}
} // this one closes onTouch
});

Android - default dark mode

I want to implement in my app Dark mode. In default I wish it been following by the system, so in Main Activity I've placed:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
It works fine, but I if user wants to change its mind and select certain option in my app menu to toggle off/on dark mode, activity is restarting and app's still following system rules. How can I change that?
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_color_mode) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
else
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
return true;
}
Code responsible for option you mentioned, is within onCreate(). Mechanism that allows user to change mode is not within onCreate()
public class MainActivityextends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
When you explicitly change the dark mode, Android recreates the activity and hence calls onCreate again.
So, after you change the dark mode you won't notice a change, as AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM is called again when onCreate is called by the system.
To make this works you can save a value into SharedPreference that can be checked in onCreate before setting the system dark mode.
This can be a boolean that you can toggle when you want to manually change the dark mode.
Here is a sample
public class MainActivityextends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSystem = prefs.getBoolean("IS_SYSTEM", true);
if (isSystem) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_color_mode) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
else
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("IS_SYSTEM", false).apply();
return true;
}
}
UPDATE
that works perfect, but when I quit application and then launch again, default system mode is active although I've switched it. Is possible here to make it works in that way?
You can use another SharedPreference boolean to be saved permanently
public class MainActivityextends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSystem = prefs.getBoolean("IS_SYSTEM", true);
boolean isNight = prefs.getBoolean("IS_NIGHT", false);
if (isSystem) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else if (isNight) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_color_mode) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
prefs.edit().putBoolean("IS_NIGHT", false).apply();
} else {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
prefs.edit().putBoolean("IS_NIGHT", true).apply();
}
prefs.edit().putBoolean("IS_SYSTEM", false).apply();
return true;
}
}

language restored to it's default after restarting or rotating screen

I have an app that supports two languages, the app is working very well when i change the language, but when i restart the app or rotate the screen, language is restored to it's default.
What i'm trying to do is to save the language and then the app should work with last saved language even after restart or rotate the screen.
I did a lot of researches and found some solutions which talks about localeHelper and Application classes and other ways but anyway non of them helped me, or maybe i'm not understanding them well.
Thanks in advance.
here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkLanguage();
setContentView(R.layout.activity_profile);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Intent i;
switch(menuItem.getItemId()){
case R.id.reset_app:
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
break;
case R.id.arabic:
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("language", "ar").commit();
language("ar");
i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.english:
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("language", "en").commit();
language("en");
i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
}
return true;
}
});
Boolean isFirstRun = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("isFirstRun", true);
if (isFirstRun) {
//show MainActivity
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("isFirstRun", false).commit();
nameTextView = findViewById(R.id.name);
nameTextView.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("name", ""));
mobileTextVew = findViewById(R.id.mobile_number);
mobileTextVew.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("mobile", ""));
idTextView = findViewById(R.id.id);
idTextView.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("id", ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public void language(String langCode){
Resources res = getResources();
String languageToLoad = langCode;
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
res.updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
public void checkLanguage(){
String langCode = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("language",null );
if(langCode == "ar")
language(langCode);
else if(langCode == "en")
language(langCode);
else
return;
}
}
In checkLanguage use compareTo (or equals) not reference equality (==) for all your string comparisons ('ar', 'en'...).
if (langCode.compareTo("ar") == 0) {
...
}
or
if (langCode.equals("ar")) {
}
See https://stackoverflow.com/a/513839/2711811

Constant listener for Boolean - Java Android

In my android app, I'm trying to check whether a boolean has changed and if it has then do something. But it's not constantly checking it. I believe I need a listener, but I'am unaware on how to structure it or where to put it. I've looked online and can really only find onClicks etc, no boolean ones.
Here is what I have so far:
public boolean gameStartTouch = false;
public boolean titleVisible = true;
/*
public boolean isJumping = false;
public boolean isGrounded = false;
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_main);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
if (gameStartTouch == false) {
gameStartTouch = true;
titleVisible = false;
}
break;
}
return true;
}
and this is what needs to go in the listener:
ImageView titleView = (ImageView) findViewById(R.id.titleImg);
ImageView startNotifView = (ImageView) findViewById(R.id.startNotifImg);
if (titleVisible == false) {
titleView.setVisibility(View.INVISIBLE);
startNotifView.setVisibility(View.INVISIBLE);
} else {
titleView.setVisibility(View.VISIBLE);
startNotifView.setVisibility(View.VISIBLE);
}
Thanks in advance. I couldn't find much info on it for these circumstances specifically.
Do some modifying to your code, manage it like so
#Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
titleView.setVisibility(View.INVISIBLE);
startNotifView.setVisibility(View.INVISIBLE);
break;
}
return true;
}
I would put your findViewById() calls in onCreate to avoid unnecessary resource fetching. The only thing I see is that you are only actually switching your booleans once. Is there any other time you plan to reset gameStartTouch to false and titleVisible to true after the first touch?
#fire_head you can simply declare titleView and startNotifView as your class private members. Initialize them in onCreate method like this:
ImageView titleView = (ImageView) findViewById(R.id.titleImg);
ImageView startNotifView = (ImageView) findViewById(R.id.starting);
and access them in handleGameStartTouch method.
Sorry, I had to post it as an answer as I couldn't comment on the answer above.

togglebutton.isChecked() is not working?

I am working with an Arduino and trying use two toggle buttons to connect and enable the Arduino. I don't want to be able to press the enable button until I have connected the robot. Here is my main activity:
public class MainActivity extends Activity {
Arduino arduino = null;
ToggleButton enable, connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton connect = (ToggleButton) findViewById(R.id.buttonConnect);
ToggleButton enable = (ToggleButton) findViewById(R.id.buttonEnable);
}
public void onToggleClicked(View view) {
switch(view.getId()) {
case R.id.buttonConnect:
boolean on = ((ToggleButton) view).isChecked();
if(on){
//Take the text from editText1 and make it the IP Address
EditText text = (EditText)findViewById(R.id.editText1);
String ip = text.getText().toString();
arduino = new Arduino(ip);
arduino.connect();
arduino.disable();
} else {
arduino.disable();
arduino.disconnect();
enable.setChecked(false);
}
break;
case R.id.buttonEnable:
boolean click = ((ToggleButton) view).isChecked();
if(click && connect.isChecked()) {
arduino.enable();
}else {
System.out.println("Not Connected");
enable.setChecked(False);
arduino.disable();
}
break;
default:
break;
}
}
I know the program is not reaching the else statement in the buttonEnable case because it is not printing out "Not Connected." I have also tried to use connect.isEnabled()in my if statement but that doesn't work either. Does anybody have answer? Thank you!
Try to set on click listener to attach the code execution to you button

Categories