- Define attributes in <declare-styleable>。
- extends View,畫出自己的圖,也可取得 xml 中的設定值。
- 可在 layout xml 中引用自訂的 View。
Define attributes in <declare-styleable>。
extends View,畫出自己的圖,也可取得 xml 中的設定值。
public class CustomView extends View {
private Paint paint;
public CustomView(Context context,AttributeSet attrs) {
super(context,attrs);
paint = new Paint();
// 取出自定的 attributes from MyView.
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyView);
// 個別取出 attribute,要給預設值,以在 xml 中沒有定義時使用。
int textColor = a.getColor(R.styleable.MyView_textColor,
Color.WHITE);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
paint.setTextSize(textSize);
paint.setColor(textColor);
// Give back a previously retrieved StyledAttributes, for later re-use.
a.recycle();
}
}
可在 layout xml 中引用自訂的 View。
* Reference
- Android 中自定义控件和属性(attr.xml,declare-styleable,TypedArray)的方法和使用 - jincf2011的专栏 - 博客频道 - CSDN.NET
- Declaring a custom android UI element using XML
- public void recycle ()
沒有留言:
張貼留言