有没有办法将Cardview放入Horizo​​ntalscrollview?

时间:2015-04-15 20:38:07

标签: horizontalscrollview android-cardview

我有一个horizo​​ntalScrollView,里面有一些卡片样式视图。 卡片样式视图中有图像和文本视图。

我曾经通过手动创建一个新的linearlayout并将图像和文本以编程方式放在视图中来实现。

卡片样式代码如下:

        LinearLayout layout = new LinearLayout(getActivity()
                .getApplicationContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(PixeltoDp(100),PixeltoDp(180));
        //params.setMargins(PixeltoDp(10),PixeltoDp(5),PixeltoDp(10), PixeltoDp(5));
        params.setMargins(10,5,10,5);
        //layout.setLayoutParams(new LayoutParams(280,400));// single container
        layout.setLayoutParams(params);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.TOP);
        layout.setBackgroundResource(R.drawable.bg_card);

        final ImageView imageView = new ImageView(getActivity()
                .getApplicationContext());
        imageView............


        TextView textView = new TextView(getActivity().getApplicationContext());
        ...............

        layout.addView(imageView);
        layout.addView(textView);

        return layout;

    }

但是现在,我想使用android.support.v7.widget.CardView类来实现这个目标。所以我可以轻松地在布局/文件夹中的cardview.xml文件中自定义cardview的布局。我的cardview布局是这样的:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/movie_img"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="0.8"
        android:gravity="center_horizontal"
        android:cropToPadding="false"
        android:src="@drawable/ic_poster" />

    <TextView
        android:id="@+id/movie_title"
        android:layout_width="fill_parent"
        android:layout_height="25dp"
        android:gravity="center"
        android:ellipsize="end"
        android:singleLine="true"
        android:hint="synaptop"
        android:textSize="10sp"
        android:textColor="#e0e0e0" />
</LinearLayout>

问题是我应该如何使用布局文件?

1 个答案:

答案 0 :(得分:0)

毕竟我自己找到了答案...... 只是打开视图

    //create ur cardview here and inflate it 
    final CardView mCardView = new CardView(getActivity());
    View.inflate(getActivity(), R.layout.cardview_layout, mCardView);

    LinearLayout mCardContainer = (LinearLayout)mCardView.findViewById(R.id.card_view_container);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        mCardContainer.setBackgroundResource(R.drawable.ripple_color_borderless);
    }


    //here u just define whatever u have in ur cardview xml
    final ImageView mImageView = (ImageView) mCardView.findViewById(R.id.movie_img);
    mImageView.setTag(index);
    mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

结束,将此视图添加到horizo​​ntalScrollView。