I have cardviews that I dynamically add at runtime to a LinearLayout
(which is inside a NestedScrollView
). I set each cardview to have an onClickListener()
. When I set android:clickable="true"
under each cardview (I want the ripple animation when the user clicks the cardview), the onClickListener
only responds if I tap the margin area (15dp) above the cardview. It doesn't respond if I click the actual cardview.
When I set android:clickable="false"
the onClickListener
works as intended, responding to a press inside the cardview.
How can I get it so that the "click box" (for lack of a better phrase) is the cardview when clickable is set to true, and not the margin below it? Note that I am using the relatively new Material 3 components.
Here's the cardview xml
<com.google.android.material.card.MaterialCardView
android:id="@+id/routeCardView"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:backgroundTint="@color/Cardview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
style="?attr/materialCardViewFilledStyle">
<TextView
style="@style/cardview_header"
android:id="@+id/routeName"
android:layout_marginStart="15dp"
android:focusable="false"
android:text="Test Text" />
<TextView
style="@style/cardview_body"
android:id="@+id/cruise_description"
android:layout_marginTop="40dp"
android:layout_marginStart="15dp"
android:focusable="false"
android:text="test text" />
</com.google.android.material.card.MaterialCardView>
And here's the Java code where I actually set the on click listeners, and add the cardviews to the linear layout
if (allRoutes != null){
ArrayList<RouteCardView> routeCardViews = new ArrayList<>();
for (UserRoute ur : allRoutes){
RouteCardView cardView = new RouteCardView(this, ur);
routeCardViews.add(cardView);
//for each RouteCardView, set an onClickListener
cardView.getView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startNavigation(cardView.getRoute());
}
});
}
Collections.sort(routeCardViews, new RouteCardViewComparator());
for (RouteCardView rcv : routeCardViews){
savedCruisesLinearLayout.addView(rcv.getView());
}