4

I want to use switch button in navigation drawer for adding and removing fragment from main layout.

this my code- menuitem.xml`

<group
    android:id="@+id/drawer_group1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_timer"
        android:icon="@drawable/ic_timer"
        android:title="Timer">

    </item>

    <item
        android:id="@+id/addFragment_Bt"
        app:actionViewClass="android.widget.Switch"
        android:title="Most Used" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings"
        android:title="Settings">

    </item>
</group>`

MainActivity.class

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        switch (menuItem.getItemId()) {
            case R.id.addFragment_Bt:

                Switch switchCompat = findViewById(R.id.addMostUsed_Bt);
                switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        FragmentManager fragmentManager = getSupportFragmentManager();
                        Fragment fragment = fragmentManager.findFragmentById(R.id.Most_Used_Fragment_container);
                        if (isChecked == true) {
                            if (fragment != null) {
                                fragmentManager.popBackStack();
                            }

                        }
                    }
                });
                break;
        }
    }
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;

    }
}

for now i am just trying to remove already added fragment.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
neo
  • 71
  • 1
  • 9

3 Answers3

7

menuitem.xml

<item android:id="@+id/nav_switch"
            app:actionLayout="@layout/switch_menu"
            android:title="Send"
            android:icon="@drawable/ic_menu_send"/>

switch_menu switch_menu is layout for switch.

switch_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_id"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:text=""/>
</LinearLayout>

Access Switch into activity:--

SwitchCompat switch_id;

switch_id =  actionView.findViewById(R.id.switch_id);
        switch_id.setChecked(true);
        switch_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), switch_id.isChecked()? "is checked!!!" : "not checked!!!",Toast.LENGTH_SHORT).show();
            }
        });

The output using above code is:

enter image description here

I hope its work for you.

Android Geek
  • 8,956
  • 2
  • 21
  • 35
2

This Works for me.

///This is menu item.

<item
     android:id="@+id/darkModeMenu"
     android:title="Dark Mode"
     android:icon="@drawable/ic_darkmode"
     app:actionViewClass="androidx.appcompat.widget.SwitchCompat"
     ></item>

//write this on the on create() method of Activity.

val menuItem = navigationView.menu.findItem(R.id.darkModeMenu)
    val switch_id = menuItem.actionView as SwitchCompat
    switch_id.setChecked(true)
    switch_id.setOnClickListener(View.OnClickListener {
        Toast.makeText(
            applicationContext,
            if (switch_id.isChecked()) "is checked!!!" else "not checked!!!",
            Toast.LENGTH_SHORT
        ).show()
    })
1

I tried these methods but not works. After an hour of research. Finally, I found an answer.

Keep the focus on my point

First, add switch in the activity_main_drawer. Where your other drawer menu items

       <item
            android:id="@+id/app_bar_switch"
            android:title="Switch"
            app:actionLayout="@layout/switch_item"
            app:showAsAction="always" />

and add below is XML by creating @layout/switch_item. Make sure to add id @+id/darkModeSwitch to your switch button. If XML creates automatically then just add the id to switch button.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Switch
        android:id="@+id/darkModeSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        tools:ignore="UseSwitchCompatOrMaterialXml" />
</RelativeLayout>

And finally, add the below java code

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Code starts here
        NavigationView navigationView = binding.navView; // your navigation drawer id
        MenuItem menuItem = navigationView.getMenu().findItem(R.id.app_bar_switch); // first insialize MenuItem 
        @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchButton = (Switch) menuItem.getActionView().findViewById(R.id.darkModeSwitch); 
        // if you are using Switch in your @layout/switch_item then use Switch or use SwitchCompact
        switchButton.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b){
                Toast.makeText(this, "True", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this, "False", Toast.LENGTH_SHORT).show();
            }
        });
}

I hope it helps.

M DEV
  • 763
  • 1
  • 7
  • 20