編輯:關於 Android 開發
RecyclerView 加 CardView 是 Material Design 裡最經典的搭配之一:RecyclerView 負責滾動與 item 複用,CardView 負責那張有圓角、有陰影的卡片外觀。下面用一個新聞列表把完整鏈路走一遍。
先引入 support 庫(v7 recyclerview 與 cardview):

compile 'com.android.support:cardview-v7:23.x.x' compile 'com.android.support:recyclerview-v7:23.x.x'
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="3dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/news_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/news_info_photo"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentTop="true"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/news_info_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/news_info_photo"
android:padding="5dp"
android:textSize="20sp" />
</RelativeLayout>
<TextView
android:id="@+id/news_info_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/news_header"
android:layout_margin="15dp"
android:lineSpacingExtra="5dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="3dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/news_header"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/news_photo"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:maxLines="1"
android:padding="5dp"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
<TextView
android:id="@+id/news_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/news_header"
android:layout_margin="15dp"
android:maxLines="2" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/news_desc"
android:orientation="horizontal">
<Button
android:id="@+id/btn_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:background="#00000000"
android:text="SHARE" />
<Button
android:id="@+id/btn_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:text="READ MORE"
android:textColor="#7AD3E0" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
這裡有兩個細節值得注意:app:cardElevation 控制陰影深度,數值越大卡片「浮」得越高;android:foreground="?android:attr/selectableItemBackground" 則給卡片加上了 Material 風格的點擊水波紋回饋。
package com.zps.recyclerviewdemo;
import java.io.Serializable;
public class News implements Serializable {
private String title;
private String desc;
private int photoId;
public News(String title, String desc, int photoId) {
this.title = title;
this.desc = desc;
this.photoId = photoId;
}
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDesc() { return desc; }
public void setDesc(String desc) { this.desc = desc; }
public int getPhotoId() { return photoId; }
public void setPhotoId(int photoId) { this.photoId = photoId; }
}
實現 Serializable 是為了後面能通過 Intent 把整個對象傳到詳情頁。
package com.zps.recyclerviewdemo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter
extends RecyclerView.Adapter<RecyclerViewAdapter.NewsViewHolder> {
private List<News> newses;
private Context context;
public RecyclerViewAdapter(List<News> newses, Context context) {
this.newses = newses;
this.context = context;
}
static class NewsViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
ImageView newsPhoto;
TextView newsTitle;
TextView newsDesc;
Button share;
Button readMore;
NewsViewHolder(final View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card_view);
newsPhoto = (ImageView) itemView.findViewById(R.id.news_photo);
newsTitle = (TextView) itemView.findViewById(R.id.news_title);
newsDesc = (TextView) itemView.findViewById(R.id.news_desc);
share = (Button) itemView.findViewById(R.id.btn_share);
readMore = (Button) itemView.findViewById(R.id.btn_more);
// 標題壓在圖片上,加一層半透明底色提升可讀性
newsTitle.setBackgroundColor(Color.argb(20, 0, 0, 0));
}
}
@Override
public NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.news_item, viewGroup, false);
return new NewsViewHolder(v);
}
@Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
final int pos = position;
holder.newsPhoto.setImageResource(newses.get(pos).getPhotoId());
holder.newsTitle.setText(newses.get(pos).getTitle());
holder.newsDesc.setText(newses.get(pos).getDesc());
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsActivity.class);
intent.putExtra("News", newses.get(pos));
context.startActivity(intent);
}
});
holder.share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
intent.putExtra(Intent.EXTRA_TEXT, newses.get(pos).getDesc());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(intent, newses.get(pos).getTitle()));
}
});
holder.readMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsActivity.class);
intent.putExtra("News", newses.get(pos));
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return newses.size();
}
}
這裡用了一個小技巧:final int pos = position;。如果不這麼做而直接在匿名內部類裡引用 position,在複用機制下存在拿到錯誤下標的風險,把當前綁定的位置固化下來更安全。
package com.zps.recyclerviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
public class NewsActivity extends AppCompatActivity {
private ImageView newsPhoto;
private TextView newsTitle;
private TextView newsDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
newsPhoto = (ImageView) findViewById(R.id.news_info_photo);
newsTitle = (TextView) findViewById(R.id.news_info_title);
newsDesc = (TextView) findViewById(R.id.news_info_desc);
News item = (News) getIntent().getSerializableExtra("News");
newsPhoto.setImageResource(item.getPhotoId());
newsTitle.setText(item.getTitle());
newsDesc.setText(item.getDesc());
}
}
package com.zps.recyclerviewdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<News> newsList;
private RecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
initPersonData();
adapter = new RecyclerViewAdapter(newsList, this);
recyclerView.setAdapter(adapter);
}
private void initPersonData() {
newsList = new ArrayList<>();
newsList.add(new News(getString(R.string.news_one_title),
getString(R.string.news_one_desc), R.mipmap.ic_launcher));
newsList.add(new News(getString(R.string.news_two_title),
getString(R.string.news_two_desc), R.mipmap.ic_launcher));
newsList.add(new News(getString(R.string.news_three_title),
getString(R.string.news_three_desc), R.mipmap.ic_launcher));
newsList.add(new News(getString(R.string.news_four_title),
getString(R.string.news_four_desc), R.mipmap.ic_launcher));
}
}
相比 ListView,RecyclerView 把「怎麼排」抽成了 LayoutManager,把「item 有什麼動畫」抽成了 ItemAnimator,Adapter 只關心數據與視圖的綁定,職責邊界清楚很多。另外 setHasFixedSize(true) 是一個容易忽略的優化:當你確定 Adapter 的數據變化不會影響 RecyclerView 整體尺寸時,打開它就能讓系統跳過整棵樹的重新測量。
Android 屬性動畫實作:用 Java 程式碼驅動動畫
用 Java 程式碼實現屬性動畫 除了透過 XML 檔定義動畫之外,屬性動畫也可以用 Java 程式碼來靈活控制。下面用一個簡單的位移範例帶大家走一遍。 先看佈局檔:
Android Studio 記憶體不足?調整 studio64.exe.vmoptions 的實用方法
記憶體不足的可能原因 Android Studio 效能低落或提示記憶體不足,可能來自電腦記憶體不足、開啟太多程式、專案過大,或 IDE 本身分配的堆大小太小。 調整方
Android Studio 入門:HelloWorld 建立、介面導覽與簽名打包
Android Studio 入門:HelloWorld 建立與開發環境導覽 對初次接觸 Android Studio 的開發者而言,從建立專案、認識介面到完成簽名打包,
Android BroadcastReceiver 廣播接收器詳解
Android BroadcastReceiver 廣播接收器詳解 今天我們來系統學習一下 Android 中 BroadcastReceiver 的相關知識。 Broa