Reputation: 53
I am having difficulty in changing the text color with the background color on touch (hover effect) in cardview. I have changed the background color but not the text color.
I have also tried to use selector but i didn't worked out.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="@android:color/white" />
<item android:drawable="@android:color/black"/>
</selector>
It changes the color of the text and its background
My layout
on pressing I want to change the color text with the background
Here is my LayoutCode
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f1f1f3"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
card_view:cardCornerRadius="0dp"
card_view:contentPadding="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/listhover">
<ImageView
android:id="@+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:scaleType="fitXY"
android:src="@drawable/cardviewimage_cio" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="12dp"
android:layout_marginTop="10dp"
android:layout_toEndOf="@+id/thumbnail"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/textView"
android:layout_below="@+id/textView"
android:layout_marginTop="5dp"
android:textColor="#000" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Upvotes: 0
Views: 2905
Reputation: 2049
UPDATE: Use on touch listener. Example:
cardView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
textView.setTextColor(Color.RED);
return true;
} else {
textView.setTextColor(Color.BLUE);
}
return false;
}
});
Use a selector as a background for CardView.
bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="@android:color/white" />
<item android:drawable="@android:color/black"/>
</selector>
Add it like this:
android:background="@drawable/bg_selector"
Upvotes: 3