-1

The menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/idSwitchColor"
        android:title="Switch"
        android:actionLayout="@layout/use_switch"
        app:actionViewClass="android.widget.Switch"
        app:showAsAction="always"/>
</menu>

Activity code:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        //inflater.inflate(R.menu.popupmenu, menu);
        inflater.inflate(R.menu.testmenu, menu);

        MenuItem itemSwitch = menu.findItem(R.id.idSwitchColor);
        itemSwitch.setActionView(R.layout.use_switch);
        final Switch swi= (Switch) itemSwitch.getActionView();

        swi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                if(swi.isChecked() == true) {
                    Toast.makeText(HomePage.this, "Worked", Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(HomePage.this, "Bye", Toast.LENGTH_SHORT).show();
            }
        });
return super.onCreateOptionsMenu(menu);

I tried debugging and it crashes at the OnClickListener part (at least from what I could tell, I'm not very good at this). Thanks in advance to anyone who can try and help me! Would really mean a lot

Edric
  • 24,639
  • 13
  • 81
  • 91
13fjuk
  • 1
  • Hi, ${username}, welcome to StackOverflow! Please consider adding the error log/stack trace from the crash which should be logged in Logcat, as well as a [_Minimal, Reproducible Example_](https://stackoverflow.com/help/minimal-reproducible-example) of the issue you're facing. – Edric Dec 27 '19 at 16:19
  • where do I find the error log? – 13fjuk Dec 27 '19 at 16:26
  • See this documentation from the Android Developers site: https://developer.android.com/studio/debug/am-logcat – Edric Dec 27 '19 at 16:29
  • Add `use_switch.xml` – Md. Asaduzzaman Dec 27 '19 at 16:42

1 Answers1

0

You don't need to call setActionView in java code, you already added actionView in your menu. if you want to use your layout file, make sure the root view of use_switch.xml is Switch otherwise, it will throw ClassCastException.

ClassCastException

and if you don't want to use it, you can delete this:

itemSwitch.setActionView(R.layout.use_switch);
Ehsan msz
  • 1,774
  • 2
  • 13
  • 26