Instead, you can simply use CheckedTextView.
Of course, you need to set the background image and text based on state, but not the ones (which you may have already used), this is a good alternative solution.
here's a sample code if you skip the textOn and textOff attributes:
CheckableTextView.java:
public class CheckableTextView extends CheckedTextView { private CharSequence mTextOn, mTextOff; public CheckableTextView (final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CheckableTextView, defStyle, 0); mTextOn = a.getString(R.styleable.CheckableTextView_textOn); mTextOff = a.getString(R.styleable.CheckableTextView_textOff); a.recycle(); } public CheckableTextView(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public CheckableTextView(final Context context) { this(context, null, 0); } @Override public void setChecked(final boolean checked) { super.setChecked(checked); if (mTextOn == null && mTextOff == null) return; if (checked) super.setText(mTextOn); else super.setText(mTextOff); } public void setTextOff(final CharSequence textOff) { this.mTextOff = textOff; } public void setTextOn(final CharSequence textOn) { this.mTextOn = textOn; } public CharSequence getTextOff() { return this.mTextOff; } public CharSequence getTextOn() { return this.mTextOn; } }
in res / values ββ/attr.xml:
<declare-styleable name="SyncMeCheckableTextView"> <attr name="textOn" format="reference|string" /> <attr name="textOff" format="reference|string" /> </declare-styleable>
another possible solution would be to use setClickable (false) in a ToggleButton and handle the onTouchListener when the movement action is ACTION_UP.
source share