is it possible to create a toggle button in Android that has an image but no text?
Ideally it would look like this:
Ive seen similar posts where the answer was to change the background but i want to preserve the Holo Light layout and just swap the text with an image.
I need to be able to programaticallly change the image source,
Any ideas how i would make this?
If this cant be done, is there a way i can make a normal button toggle on and off?
ToggleButton
inherits from TextView
so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@android:drawable/ic_menu_info_details"
android:gravity="center"
android:textOff=""
android:textOn=""
android:textSize="0dp" />
The result compared to regular ToggleButton
looks like
The seconds option is to use an ImageSpan
to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.
You create a plain ToggleButton
<ToggleButton
android:id="@+id/toggleButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false" />
Then set the "text" programmatially
ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);
The result here in the middle - icon is placed slightly lower since it takes the place of the text.
create toggle_selector.xml in res/drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
<item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>
apply the selector to your toggle button
<ToggleButton
android:id="@+id/chkState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toggle_selector"
android:textOff=""
android:textOn=""/>
Note: for removing the text i used following in above code
textOff=""
textOn=""
I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background
https://gist.github.com/akshaydashrath/9662072