【发布时间】:2019-11-16 04:21:56
【问题描述】:
假设我有一个自定义视图,它有一个名为 myGravity 的属性,它只有 3 个值 myStartVertical|myCenter|myEndVertical
我怎样才能做到这一点?
我的布局应该是这样的
<com.myapp.customview.MyCustomView
android:layout_width="match_parent"
android:layout_height="@dimen/auth_button_height"
android:text="I'm a custom view"
app:myGravity="myCenter"
/>
我的 attrs.xml 应该是这样的
<declare-styleable name="MyCustomView">
<attr name="myGravity">
<flag name="myStartVertical" value="0x97" />
<flag name="myCenter" value="0x96" />
<flag name="myEndVertical" value="0x95" />
</attr>
</declare-styleable>
而MyCustomView.kt应该是这样的
class MyCustomView @JvmOverloads constructor(
context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0)
: ConstraintLayout(context, attributeSet, defStyleAttr) {
init{
LayoutInflater.from(context).inflate(R.layout.view_app_button, this)
attributeSet?.run {
val props = context.obtainStyledAttributes(attributeSet, R.styleable.AppButton)
try {
for (i in 0..props.indexCount) {
when (val attr = props.getIndex(i)) {
R.styleable.AppButton_android_text -> {
text = props.getString(attr) ?: ""
}
R.styleable.AppButton_textGravity -> {
// TODO: get the gravity value here
myGravity = .....
}
}
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
props.recycle()
}
}
}
TODO应该填什么?
【问题讨论】:
-
你问的是什么类型的?如果是这样,那就是
Int,所以是myGravity = props.getInt(attr, -1)。 -
是的,谢谢@MikeM。这就是我要找的。span>
标签: android android-studio android-layout kotlin android-custom-view