【问题标题】:Update Image width and Margins programmatically以编程方式更新图像宽度和边距
【发布时间】:2020-08-10 02:37:54
【问题描述】:

我有一个正在布局中显示的可绘制对象。可绘制对象具有默认属性,例如颜色和宽度。我正在创建一个数据类,以便能够在创建回收器视图时更新这些数据类。中间填充颜色的部分正在工作。但我一直坚持如何从 viewHolder 实际更新可绘制宽度和 ImageView 边距。

mydrawable.xml

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/rect_outline"
        android:src="@drawable/mydrawable"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</LinearLayout>

数据类

data class ImageData(
    val c: String
    val width: Int
    val marginLeft : Int

)

MyViewHoler.kt

internal class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: ImageData) {
   itemView.rect_outline.setColorFilter(Color.parseColor(item.c))

}

}

【问题讨论】:

标签: android kotlin android-recyclerview rx-kotlin data-class


【解决方案1】:

首先将其放入您的 xml 图像视图组件中

android:scaleType="fitCenter"

我的建议是使用带有动画的比例来更好地寻找用户

imageView.animate()
                    .scaleX(scaleValue)
                    .scaleY(scaleValue)
                    .setDuration(MOVING_ANIMATION_DURATION)
                    .start()
imageView.invalidate()

但您可以设置新的布局参数,例如:

val l =  imageView.layoutParams
            l.height =  value
            l.width = value
            imageView.layoutParams = l

你也可以这样做

    val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            params.setMargins(0, 20, 0, 40)
            params.height = 1
            params. width = 1
            imageView.layoutParams = params

【讨论】:

  • 第二种方式可以用来定位drawable资源吗?
  • 如果您将drawable设置为imageview并以编程方式执行您想做的事情,drawable将按照您想要的方式运行
  • @PizzaParty123 抱歉把它放到你的 xml android:scaleType="fitCenter" imageview 中
猜你喜欢
  • 1970-01-01
  • 2011-04-08
  • 2011-05-27
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2017-03-17
相关资源
最近更新 更多