【问题标题】:Create customview with dynamic values使用动态值创建自定义视图
【发布时间】:2020-08-01 18:57:21
【问题描述】:

我正在创建一个自定义视图,该图像视图和文本是动态设置的,就像一个带有 imageView 和该框值的框。这是我的自定义视图:

class MyBoxImage@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ConstraintLayout(context, attrs, defStyleAttr) {


    init {
        LayoutInflater.from(context).inflate(R.layout.my_box_item, this, true)
    }

}

这里是说

以下函数都不能使用提供的参数调用。

是否需要在此处添加设置图片和文字的两种方法?我的布局是这样的:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="244"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.06"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/iv_face"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:src="@drawable/diamonds" />

</androidx.constraintlayout.widget.ConstraintLayout>

我的目标是创建不同的 MyBoxImage,但具有不同的 imageView 和来自 List 的不同值

【问题讨论】:

    标签: java android kotlin android-custom-view


    【解决方案1】:

    当您为任何视图充气并告诉充气机将其附加到父级时,它基本上会在父级上调用 addView 以将创建的视图添加到父级中。您可以在 link 上查看充气机的工作原理。

    因此,当您在 ConstraintLayout 中添加新的膨胀视图时,您必须将约束添加到视图中。我宁愿建议对视图进行膨胀,但不要使用适当的约束来附加和附加视图。

    要正确地将视图添加到您的约束布局,请遵循linkAdd a view programmatically in ConstraintLayout

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2012-06-26
      • 2016-04-07
      • 2011-05-24
      相关资源
      最近更新 更多