Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add listener to switch in action bar

Tags:

android

I have added switch to action bar of an activity like this

switch layout.xml is

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

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

</RelativeLayout>

Menu.xml is

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/action_settings"/>

 <item
    android:id="@+id/myswitch"
    android:title=""
    android:showAsAction="always"
    android:actionLayout="@layout/switch_layout"
/>   
</menu>

in java file i have this code

    public boolean onCreateOptionsMenu(Menu menu)
  {

    getMenuInflater().inflate(R.menu.Menu, menu);
    switch1 = (Switch) findViewById(R.id.switch1);
    if(switch1 == null){
        Toast.makeText(this, "Null", Toast.LENGTH_SHORT).show();
    }
         //     switch1.setOnCheckedChangeListener(this);
       return true;
}

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       Toast.makeText(this, "Monitored switch is " + (isChecked ? "on" : "off"),
               Toast.LENGTH_SHORT).show();
    }

public boolean onOptionsItemSelected(MenuItem item)
{

    switch (item.getItemId())
    {
    case R.id.switch1:

        Toast.makeText(this, "here", Toast.LENGTH_SHORT).show();
        break;

    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

It is showing null in toast. How can i add listener to switch in menu??

like image 318
Nalini Wanjale Avatar asked Jan 11 '23 08:01

Nalini Wanjale


1 Answers

Wrong:

Because you can't find View directly as you have taken Action layout in your item.

switch1 = (Switch) findViewById(R.id.switch1);

Correct:

Switch switch1= (Switch)menu.findItem(R.id.myswitch).getActionView().findViewById(R.id.switch1);
like image 138
Paresh Mayani Avatar answered Jan 13 '23 21:01

Paresh Mayani