編輯:關於 Android 開發
實現一個類似汽車載重指示的進度條——一排豎條,已完成的顯示綠色,未完成的顯示灰色。
博客作者:It一zhai男,轉載請標明地址:https://www.cnblogs.com/ityizhainan/p/5914487.html
先看成效果:

外層留一個空的 LinearLayout 作為容器,內容全部在代碼中動態填充:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/hezai_img"
android:layout_width="12.5dp"
android:layout_height="31.5dp"/>
</LinearLayout>
package com.example.progresstest;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ProcessTest01 extends Activity {
private LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.processtest01);
ll = (LinearLayout) findViewById(R.id.ll);
setProcess(16);
}
private void setProcess(int green) {
LayoutInflater inflater = this.getLayoutInflater();
// 有進度就填充綠色圖片
for (int i = 0; i < green; i++) {
View v = inflater.inflate(R.layout.view01, null);
ImageView img = (ImageView) v.findViewById(R.id.hezai_img);
img.setImageResource(R.drawable.green);
ll.addView(v);
}
// 沒有進度就填充灰色圖片
for (int i = 0; i < 24 - green; i++) {
View v = inflater.inflate(R.layout.view01, null);
ImageView img = (ImageView) v.findViewById(R.id.hezai_img);
img.setImageResource(R.drawable.gray);
ll.addView(v);
}
}
}


最終效果:

優缺點:思路直白、易於理解,且由於複用了同一份素材,內存佔用不高、運行流暢。缺點是擴展性差——想換顏色、換尺寸、調間距,都得重新切一套圖片,非常繁瑣。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.progresstest.HezaiProgress
android:layout_marginTop="20dp"
android:layout_gravity="center"
android:id="@+id/process"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</com.example.progresstest.HezaiProgress>
</LinearLayout>
標籤名是「包名 + 類名」的全限定形式,這正是自定義控件在 XML 中的引用方式。
package com.example.progresstest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class HezaiProgress extends View {
private int process = 10;
private int width, height;
private int h = 32; // 單條高度
private int w = 12; // 單條寬度
private int divideWidth = 5; // 間隔寬度
private int maxCount = 24; // 最大格數
private int processColor = Color.GREEN;
private int j = 1;
private int num = 0;
public HezaiProgress(Context context) {
this(context, null);
}
public HezaiProgress(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HezaiProgress(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/** 設置進度條高度 */
public void setProcessHeight(int h) {
this.h = (h == 0) ? 32 : h;
}
/** 設置進度條寬度 */
public void setProcessWidth(int w) {
this.w = (w == 0) ? 12 : w;
}
/** 設置間隔寬度 */
public void setDivideWidth(int divideWidth) {
this.divideWidth = divideWidth;
}
/** 設置最大格數 */
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
public int getProcess() {
return process;
}
/** 設置進度 */
public void setProcess(int process) {
this.process = process;
}
public int getProcessColor() {
return processColor;
}
/**
* 自定義顏色,傳入形如 "#ffffff" 的字符串
*/
public void setProcessColor(String processColor) {
char c = processColor.charAt(0);
int r = 0, g = 0, b = 0;
int rgb = Color.GREEN; // 默認綠色
if (c == '#') {
for (int i = 1; i < processColor.length(); i++) {
c = processColor.charAt(i);
if (i < 3) {
r += rOrgOrb(c, i);
} else if (i < 5) {
g += rOrgOrb(c, i);
} else {
b += rOrgOrb(c, i);
}
}
rgb = Color.rgb(r, g, b);
}
this.processColor = rgb;
}
/** 解析單個十六進制字符,按位權累加 */
private int rOrgOrb(char c, int i) {
num++;
char b = 0;
if (c >= '0' && c <= '9') {
if (i == j) b += Integer.valueOf(c) * 16; // 高四位
if (i == j + 1) b += Integer.valueOf(c); // 低四位
}
if (c >= 'A' && c <= 'F') {
if (i == j) b += ((int) c - 55) * 16;
if (i == j + 1) b += (int) c - 55;
}
if (c >= 'a' && c <= 'f') {
if (i == j) b += ((int) c - 87) * 16;
if (i == j + 1) b += (int) c - 87;
}
if (num % 2 == 0) {
j = j + 2;
}
return b;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setHezai(process, canvas);
}
private void setHezai(int process, Canvas canvas) {
Rect rect;
Paint paint;
int tmp = 2;
// 若總寬度超出控件寬度,只畫整數格
if (process * (w + tmp) + tmp > width) {
process = width / (w + divideWidth);
}
// 已完成部分
for (int i = 0; i < process; i++) {
rect = new Rect(tmp, 2, w + tmp, h);
paint = new Paint();
tmp = tmp + w + divideWidth;
paint.setColor(processColor);
canvas.drawRect(rect, paint);
}
// 未完成部分
for (int i = 0; i < maxCount - process; i++) {
rect = new Rect(tmp, 2, w + tmp, h);
paint = new Paint();
tmp = tmp + w + divideWidth;
paint.setColor(Color.rgb(211, 211, 211));
canvas.drawRect(rect, paint);
}
}
/** dp 轉 px */
private int dipToPx(int dip) {
float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.EXACTLY
|| widthSpecMode == MeasureSpec.AT_MOST) {
width = widthSpecSize;
} else {
width = w;
}
if (heightSpecMode == MeasureSpec.AT_MOST
|| heightSpecMode == MeasureSpec.UNSPECIFIED) {
height = dipToPx(h);
} else {
height = heightSpecSize;
}
setMeasuredDimension(width, height);
}
}
代碼中已做詳細註釋,這裡補充兩個 MeasureSpec 的含義:EXACTLY 表示父容器給出了精確尺寸(如 match_parent 或具體 dp 值);AT_MOST 表示不超過父容器可用空間(如 wrap_content);UNSPECIFIED 表示父容器不限制。正確處理這三種模式,自定義控件才能在各類布局中表現正常。
package com.example.progresstest;
import android.app.Activity;
import android.os.Bundle;
public class ProcessTest extends Activity {
private HezaiProgress process;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprocesstest);
process = (HezaiProgress) findViewById(R.id.process);
process.setProcessHeight(63); // 高度
process.setProcessWidth(25); // 單格寬度
process.setDivideWidth(10); // 間隔
process.setProcessColor("#008b8b"); // 顏色
}
}

方案一的優勢在於簡單直觀、內存友好,適合進度格數固定、外觀不需要頻繁變化的場景。
方案二的優勢在於高度、寬度、間隔、顏色全部可配置,且只需一行代碼調用,擴展性遠勝前者;代價是需要自己處理測量與繪製,若頻繁刷新要注意 Paint 對象的複用。
另外值得一提的是,方案二裡手寫的十六進制顏色解析,其實可以直接用 Color.parseColor("#008b8b") 一行搞定——造輪子是為了理解原理,實戰中優先用標準 API。
Android 項目實戰(二十八):Zxing 二維碼實現與優化
Android 項目實戰(二十八):Zxing 二維碼實現與優化前言:多年之前接觸過 zxing 實現二維碼,沒想到今日項目中再次使用依然離不開它。項目裡我們通常只會用到
Android 自定義 View 實作時尚儀表盤
Android 自定義 View 實作時尚儀表盤 拿到美工效果圖後,工程師需要把設計稿轉成可運行的 View。儀表盤看似複雜,但可以拆解成外弧、粗弧、小圓、刻度、指針、矩
Android 應用內更新實作:APK 的檢查、下載與安裝
Android 應用內更新實作:APK 的檢查、下載與安裝 先看成果,整個流程包含更新提示、下載進度與安裝三個階段: 原理不複雜:向伺服器問版本號,比本地的 vers
minSdkVersion、maxSdkVersion、targetSdkVersion 與 target 差異
minSdkVersion、maxSdkVersion、targetSdkVersion 與 target 差異 Android 專案中常見的 SDK 版本設定包括 mi