11

I'm working on a project where I am currently trying to put a switch inside the applications action bar (as in the wi-fi settings : http://tinypic.com/r/2l8vt35/6 )

How can this be done?

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
SweSnow
  • 17,504
  • 10
  • 36
  • 49

1 Answers1

16

Add android:actionLayout to your <item> in your menu XML resource, pointing to a layout XML resource that has your Switch. Then, use getActionView() on the MenuItem to register listeners on changes in the switch.

Note that Switch only works on API Level 14 and higher.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • How should the xml resource be refeered to? Also, can I "reach" this switch checked state from all parts of the activity or just the menu pary? – SweSnow Jul 20 '12 at 00:11
  • @SweSnow: "How should the xml resource be refeered to?" -- I am sorry, but I do not understand the question. "Also, can I "reach" this switch checked state from all parts of the activity or just the menu pary?" -- the `Switch` is a widget. You can "reach" it from wherever you store the `Switch` object. If you put it in a data member of your activity, then your activity can get your `Switch`. Here is a sample project that puts a custom layout in the action bar: https://github.com/commonsguy/cw-omnibus/tree/master/ActionBar/ActionBarDemo – CommonsWare Jul 20 '12 at 00:17
  • The first part was about exactly how the xmk should be written. This might exolain: android:actionLayout="What text goes here". Also you said it should be "pointing to a layout xml resource" so should I just tell it android:actionLayout="@id/main" and in that case, can my main.xml layout contain something else then the switch? – SweSnow Jul 20 '12 at 11:35
  • @SweSnow: `android:actionLayout="@layout/whatever_you_want_to_call_your_layout_that_contains_the_switch"` – CommonsWare Jul 20 '12 at 11:36
  • 1
    CommonsWare, your comment is not correct. Switch was introduced with Android 4.0 (API Level 14) ! – Andi Krusch Dec 12 '12 at 12:33
  • 2
    @AndiKrusch: Ah, you are correct. `Switch` existed in API Level 11, but was not part of the public API. I have updated my answer to reflect this. Sorry for any confusion. – CommonsWare Dec 12 '12 at 12:40
  • Here is a clean backported Switch View that works back to API 7: https://github.com/BoD/android-switch-backport – dgmltn Dec 19 '12 at 08:31
  • @CommonsWare Thanks for the example project illustrating how to work with custom ActionBar views. It was very helpful! – Camille Sévigny Jun 25 '14 at 12:20