Android 自定义属性
2019-05-09 本文已影响0人
海在路上
1.位置
res/values/styles.xml
2. 定义格式:
<declare-styleable name="ExpandableTextView">
<declare-styleable name="CustomView1">
<attr name="text" format="string"/>
<attr name="intType" format="integer"/>
</declare-styleable>
3. 使用
<com.android.haigeone.ui.View.CustomView1
android:layout_width="100dp"
android:layout_height="100dp"
app:text="hahahaha"
app:intType="100"
android:background="#aaa"/>
public class CustomView1 extends View {
private static final String TAG = "CustomView1";
public CustomView1(Context context) {
super(context,null);
}
public CustomView1(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CustomView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView1);
String string = typedArray.getString(R.styleable.CustomView1_text);
Log.e(TAG,"text == " + string);
int integer = typedArray.getInteger(R.styleable.CustomView1_intType, 10);
Log.e(TAG,"int == " + integer);
int intValue = typedArray.getInt(R.styleable.CustomView1_intType,10);
}
}
format 支持类型
<attr name = "background" format = "reference" /> && android:background = "@drawable/图片ID"
<attr name = "textColor" format = "color" /> && android:textColor = "#00FF00"
<attr name = "focusable" format = "boolean" /> && android:focusable = "true"
<attr name = "layout_width" format = "dimension" /> && android:layout_width = "42dip"
name = "pivotX" format = "fraction" && android:pivotX = "200%"
// 枚举
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
android:orientation = "vertical"
// 位运算
<attr name="gravity">
<flag name="top" value="0x30" />
<flag name="bottom" value="0x50" />
<flag name="left" value="0x03" />
<flag name="right" value="0x05" />
<flag name="center_vertical" value="0x10" />
...
</attr>
android:gravity="bottom|left"
//混合类型:
<attr name = "background" format = "reference|color" />
android:background = "@drawable/图片ID" || android:background = "#00FF00"
{基本类型略}