自辨认的视图这是为了响应选择 [英] Custom Checkable View which responds to Selector
问题描述
我有一组的FrameLayout
的,我想成为可检查/选择,
I have a group of FrameLayout
which I want to be checkable/selectable,
也就是说,单击后,我想了的FrameLayout
来显示为检查
- 当pressed再次我想它成为联合国检查
。更重要的是,我想这种视觉阙被描述像往常一样通过,虽然使用了<选择>
That is, after a click I would like the FrameLayout
to display as checked
- when pressed again I would like it to become unchecked
. What's more, I want this visual que to be described as usual through though the use of a <selector>
.
我似乎无法得到这个工作 - 我不知道我错过了什么:
I can't seem to get this working - I'm not sure what I'm missing:
public class CheckableFrameLayout extends FrameLayout implements Checkable {
private boolean mChecked = false;
public CheckableFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setChecked(boolean checked) {
mChecked = checked;
refreshDrawableState();
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
的布局 CheckableFrameLayout
:
<com.test.view.CheckableFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector_horizontal"
android:clickable="true" >
选择器支持它(selector_horizontal.xml):
The selector backing it (selector_horizontal.xml):
<item android:drawable="@drawable/selector_vertical_selected" android:state_pressed="false" android:state_checked="true"/>
<item android:drawable="@drawable/selector_vertical_pressed" android:state_pressed="true" android:state_checked="false"/>
<item android:drawable="@drawable/selector_vertical_normal" android:state_pressed="false" android:state_checked="false"/>
用c的pssed STATE_ $ P $上述$ C $工作正常,但视图本身并没有变得检查(不为可检查
code被称为通过调试发现的)。
Using the above code the "state_pressed" is working fine, but the View itself is not becoming checked (not is the Checkable
code being called as discovered through debug).
推荐答案
添加以下code到可检查类的工作方式:
Adding the following code to the Checkable class works:
private static final int[] CheckedStateSet = {
android.R.attr.state_checked,
};
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CheckedStateSet);
}
return drawableState;
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
这篇关于自辨认的视图这是为了响应选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!