Android:最新版CardView的安装和使用

很多软件都使用了卡片式的布局,看上去非常美观。查了一下,大多是采用CardView这个神奇的组件实现。
翻阅大部分教程,大多数都是采用这行代码来调用cardview包

import android.support.v7.widget.CardView

耗费了很多精力,我还是无法成功安装相应的依赖。
后来发现,由于版本更新,现在的方式已经改变。代码应该改为这行:

import androidx.cardview.widget.CardView;

选中之后按Alt+回车,它会自动安装依赖
如果不行就手动安装
在build.gradle(app)文件下加一行代码

implementation 'androidx.cardview:cardview:1.0.0'

Sync Now 之后就顺利安装好了

试试效果:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="200dp">

            <ImageView
                android:layout_width="150dp"
                android:layout_height="match_parent"
                android:layout_margin="5dp"
                android:scaleType="centerCrop"
                android:src="@drawable/wdd"></ImageView>

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

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:text="欢迎关注 我有一计"
                    android:textSize="18sp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="5dp"
                    android:text="更多更好玩的奇技淫巧" />
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>


</RelativeLayout>

MainActivity.java

package cn.edu.cdut.cardview;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

public class MainActivity extends AppCompatActivity {
    
    

    private CardView cardView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cardView = (CardView) findViewById(R.id.cardView);

        cardView.setRadius(8);//设置图片圆角的半径大小

        cardView.setCardElevation(8);//设置阴影部分大小

        cardView.setContentPadding(5, 5, 5, 5);//设置图片距离阴影大小
    }
}

效果如图所示:
在这里插入图片描述
更多更有趣的内容我会放在我的个人公众号中,扫描上方图片或者搜索“我有一计”,即可发现更多更有趣的彩蛋。

猜你喜欢

转载自blog.csdn.net/qq1198768105/article/details/114609740