1. 首页
  2. 技术文章
  3. Java类库

Android 支援卡片視圖 V7 框架:建立自訂卡片布局

Android 支援卡片視圖 V7 框架:建立自訂卡片布局 在 Android 開發中,卡片視圖是一種常見的布局效果,可用於顯示物品列表、新聞項目、產品等內容。Android 支援卡片視圖 V7 框架提供了一組工具,可讓開發人員更容易地建立卡片式的介面。 首先,我們需要先確保在專案的 build.gradle 檔案中引入了 V7 支援庫: implementation 'com.android.support:cardview-v7:28.0.0' 接下來,我們將建立一個自訂的卡片布局。在 res/layout 資料夾中建立一個新的 XML 檔案,例如 card_item.xml。以下是一個簡單的例子: <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" android:layout_margin="8dp" card_view:cardCornerRadius="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="12dp"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop" android:src="@drawable/image_placeholder" /> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Card Title" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Card Description" android:textSize="16sp" /> </LinearLayout> </android.support.v7.widget.CardView> 在這個例子中,我們使用了 CardView 來包裝一個 LinearLayout,並在其中放置了一張圖片和兩個 TextView,分別用於顯示卡片的標題和描述內容。 接下來,在程式碼中,我們可以使用這個自訂的卡片布局來動態生成卡片視圖。以下是一個簡單的 Java 範例: public class MainActivity extends AppCompatActivity { private LinearLayout cardContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cardContainer = findViewById(R.id.card_container); // 動態生成三個卡片 for (int i = 0; i < 3; i++) { View cardView = LayoutInflater.from(this).inflate(R.layout.card_item, cardContainer, false); ImageView imageView = cardView.findViewById(R.id.image); TextView titleTextView = cardView.findViewById(R.id.title); TextView descriptionTextView = cardView.findViewById(R.id.description); // 設定卡片的內容 imageView.setImageResource(R.drawable.card_image); titleTextView.setText("Card " + (i+1)); descriptionTextView.setText("This is the description for Card " + (i+1)); cardContainer.addView(cardView); } } } 在這個範例中,我們先找到一個 LinearLayout,然後使用 LayoutInflater 動態生成三個自訂的卡片視圖,並將其添加到容器中。我們也可以根據需要更改卡片的內容。 這樣就完成了使用 Android 支援卡片視圖 V7 框架建立自訂卡片布局的過程。開發人員可以根據自己的需求進一步加強卡片視圖的功能和外觀。
Read in English