編輯:關於 Android 程式設計
研究自訂 View 的過程中,看到有作者用 ViewGroup 實作浮動標籤,於是照著思路並加入自己的想法,做了一版自己的版本。目前支援動態新增標籤與點擊回應。
首先是 onMeasure:需要測出 ViewGroup 的寬與高,重點在於當寬度設為 wrap_content 時該怎麼辦。做法是讓每個子 View 先自我測量,再透過 getMeasuredWidth() 與 getMeasuredHeight() 取得尺寸。每加入一個子 View 前,都要判斷「當前行還塞得下嗎」;塞不下就換行,並記錄當前行的最大高度。
再來是 onLayout:核心任務是為每個子 View 定出盒模型的兩個對角點——左上角 (l, t) 與右下角 (r, b),位置就確定了。
/**
* 流式標籤:依傳入的資料動態產生標籤
*/
public class DynamicTagFlowLayout extends ViewGroup {
private List<String> mTags = new ArrayList<String>();
public DynamicTagFlowLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DynamicTagFlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DynamicTagFlowLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int totalHeight = 0; // ViewGroup 總高度
int maxLineWidth = 0; // 所有行中的最大寬度
int lineMaxHeight = 0; // 當前行的最大高度
int currentLineWidth = 0; // 當前行的總寬度
int childViewWidthSpace = 0;
int childViewHeightSpace = 0;
int count = getChildCount();
MarginLayoutParams layoutParams;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
// 先讓子 View 測量自己
measureChild(child, widthMeasureSpec, heightMeasureSpec);
layoutParams = (MarginLayoutParams) child.getLayoutParams();
childViewWidthSpace = child.getMeasuredWidth()
+ layoutParams.leftMargin + layoutParams.rightMargin;
childViewHeightSpace = child.getMeasuredHeight()
+ layoutParams.topMargin + layoutParams.bottomMargin;
if (currentLineWidth + childViewWidthSpace > widthSize) {
// 加入這個子 View 會超出寬度上限,需要換行
totalHeight += lineMaxHeight;
if (maxLineWidth < currentLineWidth) {
maxLineWidth = currentLineWidth;
}
currentLineWidth = childViewWidthSpace;
lineMaxHeight = childViewHeightSpace;
} else {
// 當前行還能繼續放
currentLineWidth += childViewWidthSpace;
if (lineMaxHeight < childViewHeightSpace) {
lineMaxHeight = childViewHeightSpace;
}
}
}
}
setMeasuredDimension(
widthMode == MeasureSpec.EXACTLY ? widthSize : maxLineWidth,
heightMode == MeasureSpec.EXACTLY ? heightSize : totalHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int currentLine = 1; // 目前是第幾行
List<Integer> lineMaxHeightList = new ArrayList<Integer>(); // 每行最大高度
int childViewWidthSpace = 0;
int childViewHeightSpace = 0;
int lineMaxHeight = 0;
int currentLineWidth = 0;
int count = getChildCount();
MarginLayoutParams layoutParams;
for (int i = 0; i < count; i++) {
int cl = 0, ct = 0, cr = 0, cb = 0;
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
layoutParams = (MarginLayoutParams) child.getLayoutParams();
childViewWidthSpace = child.getMeasuredWidth()
+ layoutParams.leftMargin + layoutParams.rightMargin;
childViewHeightSpace = child.getMeasuredHeight()
+ layoutParams.topMargin + layoutParams.bottomMargin;
if (currentLineWidth + childViewWidthSpace > getWidth()) {
// 換行:先把這一行的高度存起來
lineMaxHeightList.add(lineMaxHeight);
currentLine++;
currentLineWidth = childViewWidthSpace;
lineMaxHeight = childViewHeightSpace;
cl = layoutParams.leftMargin;
if (currentLine > 1) {
for (int j = 0; j < currentLine - 1; j++) {
ct += lineMaxHeightList.get(j);
}
ct += layoutParams.topMargin;
} else {
ct = layoutParams.topMargin;
}
} else {
// 留在當前行
cl = currentLineWidth + layoutParams.leftMargin;
if (currentLine > 1) {
for (int j = 0; j < currentLine - 1; j++) {
ct += lineMaxHeightList.get(j);
}
ct += layoutParams.topMargin;
} else {
ct = layoutParams.topMargin;
}
currentLineWidth += childViewWidthSpace;
if (lineMaxHeight < childViewHeightSpace) {
lineMaxHeight = childViewHeightSpace;
}
}
cr = cl + child.getMeasuredWidth();
cb = ct + child.getMeasuredHeight();
child.layout(cl, ct, cr, cb);
}
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
public void setTags(List<String> tags) {
if (tags == null) return;
mTags.clear();
mTags.addAll(tags);
for (int i = 0; i < mTags.size(); i++) {
TextView tv = new TextView(getContext());
MarginLayoutParams lp = new MarginLayoutParams(
MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT);
lp.setMargins(15, 15, 15, 15);
tv.setLayoutParams(lp);
tv.setBackgroundResource(R.drawable.tv_bg);
/*
* setPadding 一定要放在 setBackgroundResource 之後才有效
* https://stackoverflow.com/questions/18327498/setting-padding-for-textview-not-working
*/
tv.setPadding(15, 15, 15, 15);
tv.setTextColor(Color.WHITE);
tv.setText(mTags.get(i));
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onClick(v);
}
}
});
addView(tv);
}
requestLayout();
}
private OnTagItemClickListener listener;
public interface OnTagItemClickListener {
void onClick(View v);
}
public void setOnTagItemClickListener(OnTagItemClickListener l) {
listener = l;
}
}
程式碼裡那行註解值得留意:setPadding 必須在 setBackgroundResource 之後呼叫,順序顛倒會失效,這是很容易踩到的小坑。
public class MainActivity extends Activity {
private DynamicTagFlowLayout dynamicTagFlowLayout;
List<String> tags = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tagflowlayout);
dynamicTagFlowLayout = (DynamicTagFlowLayout) findViewById(R.id.dynamic_tag);
dynamicTagFlowLayout.setOnTagItemClickListener(new OnTagItemClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) v;
Toast.makeText(MainActivity.this, tv.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
initData();
dynamicTagFlowLayout.setTags(tags);
}
private void initData() {
tags.add("Android 開發");
tags.add("新聞熱點");
tags.add("I love you");
tags.add("Hello World");
// ...其餘標籤依此類推
}
}
呼叫 setTags() 之後,元件會依資料筆數動態產生對應數量的 TextView,並自動完成換行排版。
Android 消息機制深度解析:Handler、Looper、MessageQueue 源碼全通關
接觸 Android 的第一天就聽說了「消息機制」,但那時候的理解僅止於看看別人的博客、記住幾個類名而已,從未真正深入。最近重新過了一遍消息機制和相關源碼,這裡做個系統
Android 記事本專案(11):加入資料庫持久化
前面十節已經完成了記事本的大部分功能:拍照、加圖片、錄音、繪圖、手寫。底部選單還有一個「更多」等日後擴充。 但有一個根本問題還沒解決——寫完的記事關掉 App 之後就消失
Android 視頻處理:為錄製影片加入動態時間水印
在部分影音應用中,需求不只是畫面上顯示時間,而是要把時間資訊直接燒錄進影片畫面。這代表影片在電腦或其他裝置播放時,也能看到每一段畫面的時間標記。本文整理在 Android
Android 開發:APK 反編譯與防止反編譯(代碼混淆)
防止反編譯是每个開發者的必修課。辛辛苦苦做出來的應用,被別人三兩下反編譯並改頭換面,是件尷尬又洩氣的事。那麼該怎麼防?這裡用 Google Android 自帶的代碼混淆