问题
I want to have the following: a textview that .)changes its background when clicked .)maintains that background until it is clicked again
it all comes down to the "checkable" state, but i couldnt figure out how this exactly works. here is the xml i am using for background:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="@drawable/menuselected"
android:state_pressed="true" />
<!-- checked -->
<item android:drawable="@drawable/menuselected"
android:state_checked="true" />
<!-- default -->
<item android:drawable="@drawable/transpixel"/>
</selector>
Update: it partly works now. I adopted most of the code from http://kmansoft.com/2011/01/11/checkable-image-button/ for my custom Textview. I did this as actually, I need the functionality of a radio button as well. Now I can check a Textview, but I cant uncheck it. Does anybody see why that could be the case?
回答1:
You can use CheckedTextView with checkMark null and background your selectable
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkMark="@null"
android:background="@drawable/selectable"/>
your selectable can be
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/selector" />
</selector>
回答2:
Make a custom TextView
implementing android.widget.Checkable interface. That should be sufficient to make your selector work.
Below is the example implementation:
public class CheckableTextView extends TextView implements Checkable {
private boolean isOn=false;
public CheckableTextView(Context context) {
super(context);
}
public CheckableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
public void setChecked(boolean checked) {
isOn=checked;
refreshDrawableState();
}
@Override
public boolean isChecked() {
return isOn;
}
@Override
public void toggle() {
isOn=!isOn;
refreshDrawableState();
}
}
来源:https://stackoverflow.com/questions/16648793/android-how-to-have-a-clickable-and-checkable-textview