[Android] Custom View

Stanley Lin
Sep 4, 2018 · 5 min read

因為最近常常要做自定義view,特別寫一編來做紀錄

自定義view基本來說有幾個步驟

  1. 自定義屬性
  2. 自定義方法
  • 自定義屬性

通常自定義屬性會寫在/values/attr.xml文件中

<resources>
<declare-styleable name="EditTextLoginInput">
<attr name="loginInputType" format="string"/>
<attr name="loginInputHint" format="string"/>
<attr name="loginInputIcon" format="reference"/>
</declare-styleable>
<resources>
常用的format type:
1) string:字符串类型;
2) integer:整数类型;
3) float:浮点型;
4) dimension:尺寸,后面必须跟dp、dip、px、sp等单位;
5) Boolean:布尔值;
6) reference:引用类型,传入的是某一资源的ID,必须以“@”符号开头;
7) color:颜色,必须是“#”符号开头;
8) fraction:百分比,必须是“%”符号结尾;
9) enum:枚举类型

接著新增一個class看你要繼承LinearLayout/RelativeLayout

當繼承layout 時他會強迫你增加constuct

一般來說會有三個constuct

public CustomMenu(Context context) { …… }上面方法通常是在new的
public CustomMenu(Context context, AttributeSet attrs) { …… }
上面方法通常是在我們要取得自訂義view屬性的時候會用到
public CustomMenu(Context context, AttributeSet attrs, int defStyleAttr) { …… }
上面的方法通常是不會默認調用,但我們為了統一處理,會讓她都在第三個參數做initial
如下
public EditTextLoginInput(Context context) {
this(context,null);
}

public EditTextLoginInput(Context context, AttributeSet attrs) {
this(context, attrs,0);
}

public EditTextLoginInput(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);

View view = inflate(context,R.layout.layout_login_input,this);
ImageView iv = view.findViewById(R.id.iv_login_input);
EditText ed = view.findViewById(R.id.edit_login_input);

try{
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,R.styleable.EditTextLoginInput,defStyleAttr,0);

String hint = typedArray.getString(R.styleable.EditTextLoginInput_loginInputHint);
String inputType = typedArray.getString(R.styleable.EditTextLoginInput_loginInputType);
Drawable icon = typedArray.getDrawable(R.styleable.EditTextLoginInput_loginInputIcon);


ed.setHint(hint);

if(TYPE_PWD.equals(inputType)){
ed.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else if(TYPE_EMAIL.equals(inputType)){
ed.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
}else{
ed.setInputType(InputType.TYPE_CLASS_TEXT);
}

iv.setImageDrawable(icon);

typedArray.recycle();

}catch (Exception e){
e.printStackTrace();
}

}

Stanley Lin
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade