防止ToggleButton开关状态
答
虽然我认为你可以将它标记为禁用,但我不认为这是一个好主意,因为用户习惯于这种按钮的某种语义。
如果您只想显示某种状态,为什么不使用ImageView并根据状态显示不同的图像?
答
您可以实施自己的ToggleButton
,并使用空体覆盖toggle()
方法。
答
您可以简单地使用CheckedTextView代替。
当然,您需要根据状态设置背景图像和文本,但除了那些(您可能已经使用过)以外,这是一个很好的替代解决方案。
这里的情况下,示例代码你错过了纹元和textOff属性:
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;
}
}
在res /价值/ attr.xml
:
<declare-styleable name="SyncMeCheckableTextView">
<attr name="textOn" format="reference|string" />
<attr name="textOff" format="reference|string" />
</declare-styleable>
另一可能的解决方案是在ToggleButton上使用setClickable(false),并在动作动作为ACTION_UP时处理onTouchListener。
我用tgl.setChecked(!tgl.isChecked());在我的onClick监听器中。 (tgl os ToggleButton视图) – 2016-03-02 19:54:23