編輯:關於 Android 程式設計
寫 Android 的時候,幾乎每個人都用過 RelativeLayout、LinearLayout、FrameLayout 這三兄弟。但實務上,它們並不能滿足所有需求,於是就出現了自訂 Layout 的場景。自訂 Layout 有幾個明顯好處:可以減少 View 的層數、讓 UI 渲染更有效率,也能實作出原生控制項做不到的效果。
這次我們拿 GitHub 上的開源專案 android-layout-samples 來當教材。要留意的是這個專案採用 Android Studio 結構,用 Eclipse 匯入會失敗——近來愈來愈多開源專案轉向 Android Studio,與其硬撐舊 IDE,不如趁機擁抱 Google 的新工具。
專案作者 Lucas Rocha 是國外相當出色的 Android 工程師。跑起來之後會發現,這個範例其實是在模仿 Twitter 的資訊流效果,圖片載入用的是 Picasso。
public class TweetCompositeView extends RelativeLayout implements TweetPresenter {
private final ImageView mProfileImage;
private final TextView mAuthorText;
private final TextView mMessageText;
private final ImageView mPostImage;
private final EnumMap mActionIcons;
public TweetCompositeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TweetCompositeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(context).inflate(R.layout.tweet_composite_view, this, true);
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mAuthorText = (TextView) findViewById(R.id.author_text);
mMessageText = (TextView) findViewById(R.id.message_text);
mPostImage = (ImageView) findViewById(R.id.post_image);
mActionIcons = new EnumMap(Action.class);
for (Action action : Action.values()) {
final ImageView icon;
switch (action) {
case REPLY:
icon = (ImageView) findViewById(R.id.reply_action);
break;
case RETWEET:
icon = (ImageView) findViewById(R.id.retweet_action);
break;
case FAVOURITE:
icon = (ImageView) findViewById(R.id.favourite_action);
break;
default:
throw new IllegalArgumentException("Unrecognized tweet action");
}
mActionIcons.put(action, icon);
}
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
@Override
public void update(Tweet tweet, EnumSet flags) {
mAuthorText.setText(tweet.getAuthorName());
mMessageText.setText(tweet.getMessage());
final Context context = getContext();
ImageUtils.loadImage(context, mProfileImage, tweet.getProfileImageUrl(), flags);
final boolean hasPostImage = !TextUtils.isEmpty(tweet.getPostImageUrl());
mPostImage.setVisibility(hasPostImage ? View.VISIBLE : View.GONE);
if (hasPostImage) {
ImageUtils.loadImage(context, mPostImage, tweet.getPostImageUrl(), flags);
}
}
}
這個自訂 UI 其實非常單純,我們平常工作也常這樣用。套路大致是:
1、繼承一個 Layout,可以是 RelativeLayout,也可以是其他 ViewGroup。
2、在建構子中 inflate 版面配置檔,同時初始化子元素。
3、補上對外的方法來更新元素,例如這裡的 update()。
對應的版面配置:
注意這個版面裡還嵌著一層 LinearLayout。在 Android 中,LinearLayout 與 RelativeLayout 都屬於比較「重」的 ViewGroup,它們會反覆量測子 View 的大小與位置,效能上自然有損耗。若想再往前一步優化,就該盡量避開這類高階 ViewGroup。
public class TweetLayoutView extends ViewGroup implements TweetPresenter {
private final ImageView mProfileImage;
private final TextView mAuthorText;
private final TextView mMessageText;
private final ImageView mPostImage;
private final EnumMap mActionIcons;
public TweetLayoutView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TweetLayoutView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(context).inflate(R.layout.tweet_layout_view, this, true);
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mAuthorText = (TextView) findViewById(R.id.author_text);
mMessageText = (TextView) findViewById(R.id.message_text);
mPostImage = (ImageView) findViewById(R.id.post_image);
mActionIcons = new EnumMap(Action.class);
for (Action action : Action.values()) {
final int viewId;
switch (action) {
case REPLY:
viewId = R.id.reply_action;
break;
case RETWEET:
viewId = R.id.retweet_action;
break;
case FAVOURITE:
viewId = R.id.favourite_action;
break;
default:
throw new IllegalArgumentException("Unrecognized tweet action");
}
mActionIcons.put(action, findViewById(viewId));
}
}
private void layoutView(View view, int left, int top, int width, int height) {
MarginLayoutParams margins = (MarginLayoutParams) view.getLayoutParams();
final int leftWithMargins = left + margins.leftMargin;
final int topWithMargins = top + margins.topMargin;
view.layout(leftWithMargins, topWithMargins,
leftWithMargins + width, topWithMargins + height);
}
private int getWidthWithMargins(View child) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
return child.getWidth() + lp.leftMargin + lp.rightMargin;
}
private int getHeightWithMargins(View child) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
return child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
}
private int getMeasuredWidthWithMargins(View child) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
return child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
private int getMeasuredHeightWithMargins(View child) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
return child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthUsed = 0;
int heightUsed = 0;
measureChildWithMargins(mProfileImage, widthMeasureSpec, widthUsed,
heightMeasureSpec, heightUsed);
widthUsed += getMeasuredWidthWithMargins(mProfileImage);
measureChildWithMargins(mAuthorText, widthMeasureSpec, widthUsed,
heightMeasureSpec, heightUsed);
heightUsed += getMeasuredHeightWithMargins(mAuthorText);
measureChildWithMargins(mMessageText, widthMeasureSpec, widthUsed,
heightMeasureSpec, heightUsed);
heightUsed += getMeasuredHeightWithMargins(mMessageText);
if (mPostImage.getVisibility() != View.GONE) {
measureChildWithMargins(mPostImage, widthMeasureSpec, widthUsed,
heightMeasureSpec, heightUsed);
heightUsed += getMeasuredHeightWithMargins(mPostImage);
}
int maxIconHeight = 0;
for (Action action : Action.values()) {
final View iconView = mActionIcons.get(action);
measureChildWithMargins(iconView, widthMeasureSpec, widthUsed,
heightMeasureSpec, heightUsed);
final int height = getMeasuredHeightWithMargins(iconView);
if (height > maxIconHeight) {
maxIconHeight = height;
}
widthUsed += getMeasuredWidthWithMargins(iconView);
}
heightUsed += maxIconHeight;
int heightSize = heightUsed + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
int currentTop = paddingTop;
layoutView(mProfileImage, paddingLeft, currentTop,
mProfileImage.getMeasuredWidth(), mProfileImage.getMeasuredHeight());
final int contentLeft = getWidthWithMargins(mProfileImage) + paddingLeft;
final int contentWidth = r - l - contentLeft - getPaddingRight();
layoutView(mAuthorText, contentLeft, currentTop,
contentWidth, mAuthorText.getMeasuredHeight());
currentTop += getHeightWithMargins(mAuthorText);
layoutView(mMessageText, contentLeft, currentTop,
contentWidth, mMessageText.getMeasuredHeight());
currentTop += getHeightWithMargins(mMessageText);
if (mPostImage.getVisibility() != View.GONE) {
layoutView(mPostImage, contentLeft, currentTop,
contentWidth, mPostImage.getMeasuredHeight());
currentTop += getHeightWithMargins(mPostImage);
}
final int iconsWidth = contentWidth / mActionIcons.size();
int iconsLeft = contentLeft;
for (Action action : Action.values()) {
final View icon = mActionIcons.get(action);
layoutView(icon, iconsLeft, currentTop, iconsWidth, icon.getMeasuredHeight());
iconsLeft += iconsWidth;
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public void update(Tweet tweet, EnumSet flags) {
mAuthorText.setText(tweet.getAuthorName());
mMessageText.setText(tweet.getMessage());
final Context context = getContext();
ImageUtils.loadImage(context, mProfileImage, tweet.getProfileImageUrl(), flags);
final boolean hasPostImage = !TextUtils.isEmpty(tweet.getPostImageUrl());
mPostImage.setVisibility(hasPostImage ? View.VISIBLE : View.GONE);
if (hasPostImage) {
ImageUtils.loadImage(context, mPostImage, tweet.getPostImageUrl(), flags);
}
}
}
對應的版面配置:
兩份版面一比就差別明顯了:TweetLayoutView 完全靠自己的 onMeasure 與 onLayout 決定子元素的尺寸與位置,和 LinearLayout、RelativeLayout 再無關係,效能提升相當可觀。
當然,我們不可能自己重寫所有 Layout,否則不如直接去 Google 上班。合理的做法是有選擇地優化 App 裡最複雜的那幾處版面,提升渲染效率。
其實 TweetLayoutView 也不是終極答案,因為裡面仍用了不少系統自帶的 ImageView 與 TextView。開啟「設定 → 開發者選項 → 顯示版面邊界」,會把目前 App 的所有版面邊界標示出來。拿 Android 版的 Gmail 來看,隨便點開一個列表,會發現 ListView 每個 item 的版面邊界都在最外層,裡面再無任何邊界——這代表 Gmail 的 item 是自己重繪的一整個 View,完全沒有使用系統的 TextView 或 ImageView。這才是真正的終極形態。
但這麼做工作量龐大,還有大量細節要處理:自己畫文字是簡單,可 TextView 的文字截斷你做得出來嗎?ImageView 裡的圖片縮放呢?
所以自訂 Layout 時,除了考慮渲染效率,也得權衡實作難度與技術風險。個人建議:只針對 App 中最卡頓的那幾處版面動刀,特別是 ListView、ViewPager 裡的 item——這些地方在低端機上確實容易掉幀,其他位置視情況處理就好。
Android 4.4 以上取得圖片真實路徑:處理兩種 Uri 格式
Android 4.4(KitKat)更換了文件選擇器,回傳的 Uri 格式與早期版本不同,導致一堆「相簿選圖後拿不到路徑」的舊程式碼直接失效。問題的核心是同一個動作可能
Android 學習教程:周視圖日曆庫 WeekView 使用詳解(第十五篇)
本篇筆記聚焦於一個靈活的周視圖日曆庫 WeekView,帶大家實現以「天/周」為單位的日程展示。示例包含本地假數據填充與異步網絡加載兩種模式,並支持日、三日、周多種視圖切
Android Activity 的註冊配置、啟動與關閉全解析
先看一個最直觀的演示: Activity 在四大組件中的位置 Android 提供 Activity、Service、Broadcast Receiver、Conten
以 MVP 架構實作 Android 輪播圖 Banner
需求與準備 本篇以 MVP 模式實作輪播圖,目標是讓 Banner 的資料載入、業務邏輯與畫面顯示職責分明。實作前先加入 Banner、Retrofit 與 Glide