Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
currently i want to create a switch inside my navigation drawer such that when enabled the dark mode would be enabled throughout my entire app. However though the first issue for which i have encountered is my Home screen there is already a switch as seen here

but i already have a switch already included in my navigation drawer already, is there anyway to be able to remove the switch from the Homescreen and ensure that the only switch that i would have would be in the Navigation drawer such that when enabled it would enable dark mode for my app?

here is my code for activity_main:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:id="@+id/drawer"
    tools:context=".MainActivity">

    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/drawabletoolbar"/>
    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/content_main"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_alignParentBottom="false">

        <Switch
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btnSwitch"
            android:text=""/>



    </LinearLayout>



    <com.google.android.material.navigation.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/navi_view"
        app:menu="@menu/drawable_menu"
        app:headerLayout="@layout/drawable_header"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"/>

</androidx.drawerlayout.widget.DrawerLayout>


here is my code for the layout file for which i have created the switch in


<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
="" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">

<switch
android:layout_width="fill_parent"
="" android:layout_height="match_parent" android:text="" android:id="@+id/btnSwitch">



and here is my MainActivity code

package sg.edu.rp.c346.app4thnewspd;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.widget.Toolbar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import sg.edu.rp.c346.app4thnewspd.Model.Articles;
import sg.edu.rp.c346.app4thnewspd.Model.Headlines;

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
final String API_KEY = "5353a8d609b4415ab6f449f31d46926a";
Adapter adapter;
List<articles>articles = new ArrayList<>();
private String query;
Toolbar toolbar;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
private Switch btnSwitch;

public static final String MYPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNIghtMode";
SharedPreferences sharedPreferences;



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);



drawer = findViewById(R.id.drawer);
toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.open,R.string.close);
drawer.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();


swipeRefreshLayout = findViewById(R.id.swipeRefresh);
recyclerView = findViewById(R.id.recyclerView);

etQuery = findViewById(R.id.etQuery);
btnSearch = findViewById(R.id.btnSearch);

sharedPreferences = getSharedPreferences(MYPREFERENCES, Context.MODE_PRIVATE);
btnSwitch = findViewById(R.id.btnSwitch);

checkNightModeActivated();

btnSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});





recyclerView.setLayoutManager(new LinearLayoutManager(this));
final String country = getCountry();

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson("",country,API_KEY);
}
});

retrieveJson("",country, API_KEY);

btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")){
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(),country,API_KEY);
}
});
retrieveJson(etQuery.getText().toString(),country,API_KEY);
}else{
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
retrieveJson("",country,API_KEY);
}
});
retrieveJson("",country,API_KEY);
}
}
});
}

private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putBoolean(KEY_ISNIGHTMODE,nightMode);

editor.apply();
}
public void checkNightModeActivated(){
if(sharedPreferences.getBoolean(KEY_ISNIGHTMODE, false)){
btnSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
btnSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}


private void restartActivity() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}


private String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}


public void retrieveJson(final String query, final String country, final String apiKey){


swipeRefreshLayout.setRefreshing(true);
Call<headlines>call;
if(!etQuery.getText().toString().equals("")){
call = ApiClient.getInstance().getApi().getSpecificData(query,apiKey);
}else{
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<headlines>() {
@Override
public void onResponse(Call<headlines> call, Response<headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null){
swipeRefreshLayout.setRefreshing(false);
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(MainActivity.this,articles);
recyclerView.setAdapter(adapter);

}
}

@Override
public void onFailure(Call<headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}

What I have tried:

so currently in my layout file for which i have created for the switch

<item
       android:id="@+id/Mode"
       app:actionLayout="@layout/layout_switch"
       android:icon="@drawable/ic_brightness_4_black_24dp"
       android:title="Dark Mode" />


ive tried to change the actionLayout to activity_main instead but however though after the splashScreen nothing is shown its just one black screen
Posted
Updated 12-Apr-20 20:32pm
v2
Comments
David Crow 12-Apr-20 20:04pm    
Is your app Android 10 (API level 29) or higher?
MervinWee 13-Apr-20 2:30am    
yea, and i realised i did not show the error in the layout that i mentioned so here it is.
https://i.stack.imgur.com/DykAO.png

so as such you can see in the image above that i have a switch placed at the top right , but however though i already have a switch in my navigation drawer itself already. hence as such is there any way for which i could remove the switch and ensure that the only switch in existence is the one inside my navigation drawer?
David Crow 13-Apr-20 7:55am    
"...is there any way for which i could remove the switch and ensure that the only switch in existence is the one inside my navigation drawer?"

Yes, remove the <Switch> widget from the layout file.
MervinWee 13-Apr-20 8:28am    
hmm, but even after i have removed it the switch it still remains...
MervinWee 14-Apr-20 6:59am    
so currently now after making some changes to my MainActivity, i have been able to successfully allow for my switch when flipped to be able to turn on dark mode for my app, however though currently the issue now is that the only switch that is able to do what i have said so far is the switch on my home screen as seen in the image that i have shared above, but what i want is to have the switch in my navigation drawer to be able to be the one to do the change to dark mode. Hence as such could anybody assist me?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900