1
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked, };
private boolean mChecked;
public CheckableRelativeLayout(Context context) {
super(context);
}
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CheckableRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
}
我用它是这样的:在selector_background_navigation_item这样定义的列表项
<com.example.components.CheckableRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/CheckableRelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector_background_navigation_item"
android:orientation="horizontal"
android:padding="10dp"
android:gravity="center_vertical" >
<ImageView
android:id="@+id/navigationDrawerItemImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/navigationDrawerItemTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/navigationDrawerItemImageView"
android:layout_margin="5dp"
android:layout_toRightOf="@+id/navigationDrawerItemImageView"
android:textColor="@drawable/selector_text_navigation_item"
android:textSize="@dimen/text_size_small" />
</com.example.components.CheckableRelativeLayout>
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:state_pressed="false" android:drawable="@color/darkblue"></item>
<item android:state_pressed="true" android:drawable="@color/sirinblue"></item>
<item android:state_checked="true" android:drawable="@color/white"></item>
</selector>
和像这样定义的selector_text_navigation_item:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:state_pressed="false" android:color="@color/white"></item>
<item android:state_pressed="true" android:color="@color/lightblue"></item>
<item android:state_checked="true" android:color="@color/lightblue"></item>
</selector>
现在的问题是,TextView的选择并没有检查事件做出响应,而CheckableRelativeLayout做,但都正确地压简单回应,最新最好的方式来解决这一问题?也许CheckableRelativeLayout缺少一些处理其子选中状态的超级调用?