如何扩展cardview并将其作为Recyclerview中唯一的项目传递?

时间:2017-03-05 07:28:26

标签: android class android-recyclerview extend android-cardview

您好我是Android的新手我试图通过cardview& Recyclerview使用itemtouchhelper.callback,因此我需要将cardview作为RecyclerView中唯一的项目answer,但我不知道如何扩展cardView {1}}制作自定义视图?

cardStack

import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.LayoutInflater;


public class CardStack extends CardView {
  private int image;


    public CardStack(Context context) {
        super(context);
        initialize(context);
    }

    public CardStack(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public CardStack(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void initialize(Context context){
        LayoutInflater.from(context).inflate(R.layout.card,this);
        //What to do here?
    }

card.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.stocks.android.cardviewobjectswipefeaturestocks.CardStack
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/card1" />

    </com.stocks.android.cardviewobjectswipefeaturestocks.CardStack>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

易。

制作布局文件,父级为CardView。 我做了一个看起来像这个

的row_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:fillViewport="true"
    app:cardBackgroundColor="@color/OFF_WHITE"
    app:cardCornerRadius="4dp"
    app:cardElevation="2dp"
    app:cardPreventCornerOverlap="false">
<LinearLayout  android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
.........
</LinearLayout>
</CardView>

然后在你的适配器里面以这种方式将它传递给适配器:

  @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.row_list_item, parent, false));
    }

你已经完成了。奖励!