【问题标题】:How to set custom gravity attribute to custome view in android?如何在android中将自定义重力属性设置为自定义视图?
【发布时间】: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


【解决方案1】:

关于你的问题,我们有两种情况

案例 1: 您将 gravity 应用到 MyCustomView 及其父视图

EX:你把 MyCustomView 作为 LinearLayout 的子节点

val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.gravity = /* your gravity -> set gravity of your custom view with it's parent */
// myCustomView.layoutParams = layoutParams

案例 2: 您应用gravity 使MyCustomView 视图的所有子视图都位于topleft、...

EX:让MyCustomView 延伸自LinearLayout

val view = MyCustomView(this)
view.gravity = /* your gravity -> set gravity to all the child of the LinearLayout */

【讨论】:

  • 实际上,@Mike M 明白了。如果可以的话,我会将他的评论标记为已接受的答案。无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
相关资源
最近更新 更多