我使用以下选择器来更改listView项目中文本的外观:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:color="#FFFFFFFF" /> <!-- checked -->
<item android:state_activated="true"
android:color="#FFFFFFFF" /> <!-- activated -->
<item android:state_pressed="true"
android:color="#FFFFFFFF" /> <!-- pressed -->
<item android:state_focused="true"
android:color="#FFFFFFFF" /> <!-- focused -->
<item android:color="#FF000000" /> <!-- default -->
</selector>
整个选择器在Android(ICS,JB)的更高版本上工作正常,但在Gingerbread上,而在_state项目正确应用时,当我在listView上调用setItemChecked时,不应用state_checked项。
我用来设置项目的代码如下:
@Override
protected void onResume()
{
super.onResume();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
for (int index = 0; index < measureList.size(); index++)
{
if (measureList.get(index).getId() == appContext.getMeasureId())
{
getListView().setItemChecked(index, true);
}
}
}
和用于设置选择器的xml是:
<TextView
android:id="@+id/item_text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:paddingRight="10dp"
android:ellipsize="end"
android:layout_toRightOf="@id/item_thumb"
android:maxLines="1"
android:scrollHorizontally="true"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="@color/selected_text_selector"
/>
有谁知道为什么会这样?我还没有在GB和ICS之间的Android版本上测试它,但是我会尽快编辑这篇文章。
答案 0 :(得分:7)
经过一番搜索后,在我看来,state_checked
未在蜂窝前表达的原因是setActive
上的View
方法在API之前不可用级别11.这意味着已检查状态不会传播到我的布局的子视图。
关键:
TextView
换成CheckedTextView
1)XML中是一个简单的开关,2)我修改了Voicu链接的答案中的代码,提供以下内容:
public class CheckableRelativeLayout extends RelativeLayout implements Checkable
{
private boolean checked = false;
public CheckableRelativeLayout(Context context) {
super(context, null);
}
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
private static final int[] CheckedStateSet = {
R.attr.state_checked
};
@Override
protected void dispatchSetPressed(boolean pressed)
{
super.dispatchSetPressed(pressed);
setChecked(pressed);
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
for (int index = 0; index < getChildCount(); index++)
{
View view = getChildAt(index);
if (view.getClass().toString().equals(CheckedTextView.class.toString()))
{
CheckedTextView checkable = (CheckedTextView)view;
checkable.setChecked(checked);
checkable.refreshDrawableState();
}
}
refreshDrawableState();
}
public boolean isChecked() {
return checked;
}
public void toggle() {
checked = !checked;
refreshDrawableState();
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CheckedStateSet);
}
return drawableState;
}
@Override
public boolean performClick() {
return super.performClick();
}
}