简体   繁体   中英

OnClick in a CardView <include> layout

I have a xml that contains some CardView <include> , I want to set onClick in the CardView includes to open an Activity in my project. I tried to set the onClick in the CardView layout as you will see in the code below, it opens normally but triggers an error sometimes and the application stops. How can I set the onClick in this include?

This is the <include> in my xml

 <include layout="@layout/view_caderno"
            android:id="@+id/view_caderno" />

and here is the CardView

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="15dp"
android:layout_margin="5dp"
android:onClick="Caderno"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_margin="2dp"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/pic1"
        android:layout_width="100dp"
        android:layout_height="135dp"
        android:scaleType="centerCrop"
        android:padding="5dp"
        android:src="@drawable/note"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pic1"
        android:maxLines="3"
        android:text="Diário"
        android:padding="10dp"
        android:textColor="#222"
        android:textStyle="bold"
        android:textSize="22dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:maxLines="3"
        android:padding="5dp"
        android:drawableRight="@drawable/baby2"
        android:text="@string/diário"
        android:textColor="#666"
        android:textSize="14dp" />

</RelativeLayout>

You have to make OnClickListener programmatically :

       CardView yourCardView = (CardView) findViewById(R.id.view_caderno);

        yourCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do what you want on click event
            }
        });

Check this answer - stackoverflow.com/a/37790333/1333022

Dynamically you can add layout in your cardview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM