开发者

Prevent ToggleButton from switching state

I have a ToggleButton, when you click it, I don't want the state to change. I will handle state changes myself when after I receive feedback from whatever the button toggled. How might I prevent the state change on click?开发者_如何学编程


You can implement your own ToggleButton with overriden toggle() method with empty body.


You could simply use the CheckedTextView instead.

Of course, you need to set a background image and a text based on the state, but other than those (which you might have used already), it's a nice alternative solution.

here's a sample code in case you miss 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) on the ToggleButton, and handle onTouchListener when the motion action is ACTION_UP .


While I think you can just mark it as disabled, I don't think it is a good idea, as users are used to a certain semantic of such a button.

If you only want to show some state, why don't you use an ImageView and show different images depending on state?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜