pressed

android – How to use different style/color for text and image in pressed ListItem


Am working on a Android SDK 17+ app. A ListView uses a BaseAdapter instance to manage its items. Each item is a simple layout which only includes a TextView. The TextView uses its CompoundDrawable to show an icon.

How can I both change the text and icon/drawable color when an item is pressed/highlighted?

Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    listView= (ListView)findViewById(R.id.listView);
    listView.setAdapter(new MyListAdapter(this));
    ...
}

private static class MyListAdapterextends BaseAdapter {
    ...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.listitem__textItem, null);

            viewHolder = new ViewHolder();
            viewHolder.textView = (TextView)convertView.findViewById(R.id.textView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)convertView.getTag();
        }

        ...
}

static class ViewHolder {
    TextView textView;
}

listitem__textItem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ...>
    ...
    <TextView
        ...
        android:background="@drawable/itemselector_bg" 
        android:textColor="@drawable/itemselector_text"
        android:drawableTop="@drawable/someIcon"
        ... />
</RelativeLayout>

itemselector_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/blue" />
    <item android:drawable="@color/white" />
</selector>

itemselector_text.xml

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white" />
    <item android:state_focused="true" android:color="@color/white" />
    <item android:color="@color/red" />
</selector>

Problem 1:
While changing the background by using @drawable/itemselector_bg works without a problem, using @drawable/itemselector_text to change the text color does not work.

Problem 2:
How can I change the icon color when pressed/focused?



لینک منبع