アプリ開発初心者の暇つぶしAndroid体験記

アプリ開発初心者がAndroidアプリ開発始めました。日々学んだことをアウトプットしていきます。

【Android】CardViewでカード型のレイアウトを作ってみた

スマホをいじってて、「あのカードみたいなのどうやって出すんだろう」と
ふと思ったので調べてみました。
CardViewというものがあるみたいなので実装方法をまとめておきます。

依存関係の追加

build.gradleにCardView利用のための依存関係を追加します。

dependencies {
    implementation 'androidx.cardview:cardview:1.0.0'
}

レイアウトの作成

CardViewのタグをxmlに記述するだけでカード型のレイアウトが表示されます。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="15dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="CardView"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.cardview.widget.CardView>

</LinearLayout>

f:id:mtnanao:20200801110122p:plain:w250
表示されたものがこちら

少々見づらいですが、うっすらと影が表示されカード型になっています。

CardViewの属性

最低限の実装を載せましたが、属性に応じた表示の変化を見ていきます。

cardCornerRadius

カードの角に丸みをつける属性です。

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="15dp"
        app:cardCornerRadius="12dp">

f:id:mtnanao:20200801110209p:plain:w250

cardElevation

カードの高さを指定する属性です。

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="15dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="20dp">

f:id:mtnanao:20200801110241p:plain:w250

cardBackgroundColor

カードの色を変更する属性です。

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="15dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="20dp"
        app:cardBackgroundColor="@color/colorAccent">

f:id:mtnanao:20200801110302p:plain:w250

雑談

要素を重ねているようなデザインは今風でおしゃれな感じがしますね!
他にも色々と学んでみたいと思います!



それでは以上です(^_^)/


最後にアプリの宣伝させてください(*^-^*)

play.google.com