declare-styleable

Android中declare-styleable怎么使用

小亿
97
2023-07-12 11:48:45
栏目: 编程语言

在Android中,declare-styleable用于定义自定义属性集合,可以在布局文件和代码中使用这些属性。

首先,在res/values文件夹下创建一个attrs.xml文件,定义declare-styleable

<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute1" format="reference" />
<attr name="customAttribute2" format="boolean" />
<attr name="customAttribute3" format="string" />
</declare-styleable>
</resources>

然后,在布局文件中使用自定义属性:

<com.example.CustomView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttribute1="@drawable/icon"
app:customAttribute2="true"
app:customAttribute3="Hello World" />

最后,在自定义View的代码中获取这些属性值:

public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
Drawable customAttribute1 = a.getDrawable(R.styleable.CustomView_customAttribute1);
boolean customAttribute2 = a.getBoolean(R.styleable.CustomView_customAttribute2, false);
String customAttribute3 = a.getString(R.styleable.CustomView_customAttribute3);
a.recycle();
// 使用获取到的属性值进行相应操作
}
}

这样就可以在自定义View中使用declare-styleable定义的自定义属性了。

0
看了该问题的人还看了