編輯:關於 Android 程式設計
今天為大家帶來一個簡單卻相當實用的控制項 ButtonExtendM。在開發中,我們經常會用到圖片加文字的組合控制項,像這樣:

以上圖片皆擷取自微信(暫時還沒找到 icon 在下、文字在上的例子)。
下面我們透過一個控制項,就能實現上下左右全部的樣式,只需改動一個屬性值即可切換 icon 的位置,是不是很方便?先來看 Demo 效果圖:

沒錯,上圖三種不同的樣式,都是透過同一個控制項實作的。下面來看程式碼。
第一步:自訂屬性
在 res/values/ 目錄下新增 attrs.xml 檔,加入如下屬性:
<attr name="backColor" format="color" /> <attr name="backColorPress" format="color" /> <attr name="textColor" format="color" /> <attr name="textColorPress" format="color" /> <declare-styleable name="ButtonExtendM"> <attr name="backColor"/> <attr name="backColorPress"/> <attr name="textColor"/> <attr name="textColorPress"/> <attr name="iconDrawable" format="reference" /> <attr name="iconDrawablePress" format="reference" /> <attr name="text" format="string" /> <attr name="textSize" format="float" /> <attr name="spacing" format="dimension" /> <attr name="style"> <enum name="iconLeft" value="0" /> <enum name="iconRight" value="1" /> <enum name="iconUp" value="2" /> <enum name="iconBottom" value="3" /> </attr> </declare-styleable>
第二步:新增版面檔 view_button_extend_m.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/iv_icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/tv_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" android:text="@string/button_extend_m_default_text"/> </RelativeLayout>
第三步:新增 ButtonExtendM.java,繼承 RelativeLayout
package com.landptf.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.landptf.R;
import com.landptf.util.ConvertM;
/**
* Created by landptf on 2016/10/31.
* 擴展Button,支持文字和icon分上下左右四種方式顯示
* 默認為左右結構,圖片在左,文字在右
*/
public class ButtonExtendM extends RelativeLayout {
/** 左右結構,圖片在左,文字在右 */
public static final int STYLE_ICON_LEFT = 0;
/** 左右結構,圖片在右,文字在左 */
public static final int STYLE_ICON_RIGHT = 1;
/** 上下結構,圖片在上,文字在下 */
public static final int STYLE_ICON_UP = 2;
/** 上下結構,圖片在下,文字在上 */
public static final int STYLE_ICON_DOWN = 3;
/** 定義控件 */
private ImageView ivIcon;
private TextView tvContent;
/** 上下文 */
private Context mContext;
/** View的背景色 */
private int backColor = 0;
/** View被按下時的背景色 */
private int backColorPress = 0;
/** icon的背景圖片 */
private Drawable iconDrawable = null;
/** icon被按下時顯示的背景圖片 */
private Drawable iconDrawablePress = null;
/** View文字的颜色 */
private ColorStateList textColor = null;
/** View被按下時文字的顏色 */
private ColorStateList textColorPress = null;
/** 兩個控件之間的間距,默認為8dp */
private int spacing = 8;
/** 兩個控件的位置結構 */
private int mStyle = STYLE_ICON_LEFT;
/** 標示onTouch方法的返回值,用來解決onClick和onTouch沖突問題 */
private boolean isCost = true;
private OnClickListener onClickListener = null;
public interface OnClickListener {
void onClick(View v);
}
/** 設置View的Click事件
* @param l */
public void setOnClickListener(OnClickListener l) {
this.onClickListener = l;
isCost = false;
}
public ButtonExtendM(Context context) {
super(context);
mContext = context;
}
public ButtonExtendM(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ButtonExtendM(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
//加載布局
LayoutInflater.from(context).inflate(R.layout.view_button_extend_m, this, true);
//初始化控件
ivIcon = (ImageView) findViewById(R.id.iv_icon);
tvContent = (TextView) findViewById(R.id.tv_content);
setGravity(Gravity.CENTER);
TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.ButtonExtendM, defStyle, 0);
if (a != null) {
//設置背景色
ColorStateList colorList = a.getColorStateList(R.styleable.ButtonExtendM_backColor);
if (colorList != null) {
backColor = colorList.getColorForState(getDrawableState(), 0);
if (backColor != 0) {
setBackgroundColor(backColor);
}
}
//記錄View被按下時的背景色
ColorStateList colorListPress = a.getColorStateList(R.styleable.ButtonExtendM_backColorPress);
if (colorListPress != null) {
backColorPress = colorListPress.getColorForState(getDrawableState(), 0);
}
//設置icon
iconDrawable = a.getDrawable(R.styleable.ButtonExtendM_iconDrawable);
if (iconDrawable != null) {
ivIcon.setImageDrawable(iconDrawable);
}
//記錄View被按下時的icon的圖片
iconDrawablePress = a.getDrawable(R.styleable.ButtonExtendM_iconDrawablePress);
//設置文字的顏色
textColor = a.getColorStateList(R.styleable.ButtonExtendM_textColor);
if (textColor != null) {
tvContent.setTextColor(textColor);
}
//記錄View被按下時文字的顏色
textColorPress = a.getColorStateList(R.styleable.ButtonExtendM_textColorPress);
//設置顯示的文本內容
String text = a.getString(R.styleable.ButtonExtendM_text);
if (text != null) {
//默認為隱藏的,設置文字後顯示出來
tvContent.setVisibility(VISIBLE);
tvContent.setText(text);
}
//設置文本字體大小
float textSize = a.getFloat(R.styleable.ButtonExtendM_textSize, 0);
if (textSize != 0) {
tvContent.setTextSize(textSize);
}
//設置兩個控件之間的間距
spacing = a.getDimensionPixelSize(R.styleable.ButtonExtendM_spacing, ConvertM.dp2px(context, 8));
//設置兩個控件的位置結構
mStyle = a.getInt(R.styleable.ButtonExtendM_style, 0);
setIconStyle(mStyle);
a.recycle();
}
setOnTouchListener(new OnTouchListener() {
@Override public boolean onTouch(View arg0, MotionEvent event) {
//根據touch事件設置按下抬起的樣式
return setTouchStyle(event.getAction());
}
});
setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if (onClickListener != null) {
onClickListener.onClick(v);
}
}
});
}
/** 根據按下或者抬起來改變背景和文字樣式
* @param state
* @return isCost */
private boolean setTouchStyle(int state) {
if (state == MotionEvent.ACTION_DOWN) {
if (backColorPress != 0) {
setBackgroundColor(backColorPress);
}
if (iconDrawablePress != null) {
ivIcon.setImageDrawable(iconDrawablePress);
}
if (textColorPress != null) {
tvContent.setTextColor(textColorPress);
}
}
if (state == MotionEvent.ACTION_UP) {
if (backColor != 0) {
setBackgroundColor(backColor);
}
if (iconDrawable != null) {
ivIcon.setImageDrawable(iconDrawable);
}
if (textColor != null) {
tvContent.setTextColor(textColor);
}
}
return isCost;
}
/** 設置圖標位置
* 通過重置LayoutParams來設置兩個控件的擺放位置
* @param style */
public void setIconStyle(int style) {
mStyle = style;
RelativeLayout.LayoutParams lp;
switch (style) {
case STYLE_ICON_LEFT:
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
ivIcon.setLayoutParams(lp);
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
lp.addRule(RelativeLayout.RIGHT_OF, ivIcon.getId());
lp.leftMargin = spacing;
tvContent.setLayoutParams(lp);
break;
case STYLE_ICON_RIGHT:
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
tvContent.setLayoutParams(lp);
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
lp.addRule(RelativeLayout.RIGHT_OF, tvContent.getId());
lp.leftMargin = spacing;
ivIcon.setLayoutParams(lp);
break;
case STYLE_ICON_UP:
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
ivIcon.setLayoutParams(lp);
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.BELOW, ivIcon.getId());
lp.leftMargin = spacing;
tvContent.setLayoutParams(lp);
break;
case STYLE_ICON_DOWN:
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
tvContent.setLayoutParams(lp);
lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.BELOW, tvContent.getId());
lp.leftMargin = spacing;
ivIcon.setLayoutParams(lp);
break;
default:
break;
}
}
/** 設置View的背景色
* @param backColor */
public void setBackColor(int backColor) {
this.backColor = backColor;
setBackgroundColor(backColor);
}
/** 設置View被按下時的背景色
* @param backColorPress */
public void setBackColorPress(int backColorPress) {
this.backColorPress = backColorPress;
}
/** 設置icon的圖片
* @param iconDrawable */
public void setIconDrawable(Drawable iconDrawable) {
this.iconDrawable = iconDrawable;
ivIcon.setImageDrawable(iconDrawable);
}
/** 設置View被按下時的icon的圖片
* @param iconDrawablePress */
public void setIconDrawablePress(Drawable iconDrawablePress) {
this.iconDrawablePress = iconDrawablePress;
}
/** 設置文字的顏色
* @param textColor */
public void setTextColor(int textColor) {
if (textColor == 0) return;
this.textColor = ColorStateList.valueOf(textColor);
tvContent.setTextColor(this.textColor);
}
/** 設置View被按下時文字的顏色
* @param textColorPress */
public void setTextColorPress(int textColorPress) {
if (textColorPress == 0) return;
this.textColorPress = ColorStateList.valueOf(textColorPress);
}
/** 設置顯示的文本內容
* @param text */
public void setText(CharSequence text) {
//默認為隱藏的,設置文字後顯示出來
tvContent.setVisibility(VISIBLE);
tvContent.setText(text);
}
/** 獲取顯示的文本
* @return */
public String getText() {
return tvContent.getText().toString();
}
/** 設置文本字體大小
* @param size */
public void setTextSize(float size) {
tvContent.setTextSize(size);
}
/** 設置兩個控件之間的間距
* @param spacing */
public void setSpacing(int spacing) {
this.spacing = ConvertM.dp2px(mContext, spacing);
//設置完成後刷新一下兩個控件的結構,避免先執行了setIconStyle後,setSpacing不生效
setIconStyle(mStyle);
}
}
程式碼註解基本說明了實作細節,關鍵在於 setIconStyle 方法:透過重新設定 LayoutParams 的對齊規則,靈活調整 icon 與文字的擺放位置。接下來看看如何使用。
在 layout 中直接引用 ButtonExtendM 即可,注意要加上:
xmlns:landptf="https://schemas.android.com/apk/res-auto"
<com.landptf.view.ButtonExtendM android:id="@+id/bem_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="8dp" landptf:iconDrawable="@drawable/title_back" landptf:iconDrawablePress="@drawable/title_back_selected" landptf:textColor="@android:color/white" landptf:spacing="4dp" landptf:text="返回"/>
這是實作的選單欄返回按鈕,採左右結構,icon 在左為預設樣式。特別留意帶有 Press 的屬性,主要用來設定控制項被按下後的效果。
再看一個上下結構的例子:
<com.landptf.view.ButtonExtendM android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" landptf:iconDrawable="@drawable/icon_home_page" landptf:text="首頁" landptf:style="iconUp" />
只需設定 landptf:style 即可切換為上下結構,當然也可以透過 Java 程式碼來實現:
setIconStyle(ButtonExtendM.STYLE_ICON_UP)
全部程式碼已託管於開源中國的碼雲上,歡迎大家下載使用。希望這個自訂控制項能為大家的開發帶來便利。
淺析 Android 開源框架 Universal Image Loader 的用法與原始碼
在 Android 開發中,圖片顯示幾乎是每個專案都躲不掉的需求。網路上翻資料會發現,Universal Image Loader(以下簡稱 UIL)長期是這個領域的熱門
Android 混合開發:WebView 與 HTML、JavaScript 交互
Android 開發除了原生方式之外,還可以使用 WebView 加載 HTML 頁面,並與 JavaScript 進行交互。這種混合開發方式可以用於活動頁、表單頁、幫助
Android 實現長按連續響應的 Button
在電商類 App 的購物車頁面,常有這樣的需求:長按「+」或「-」按鈕時,商品數量能連續地增加或減少,而不是每按一次才變動一次。本文就來實現這個效果。 先看預覽圖: 一
自製 Android 控件實作:Well Swipe 拖拽排序與刪除動畫
最近動手寫了一個名為 Well Swipe 的客製化控件,主要解決列表項目的手勢互動問題,整體重點放在兩個體驗細節上。 核心功能 這個控件主要實現了兩件事:一是項目左右滑