【问题标题】:How to set margin for a view based on condition - Android如何根据条件为视图设置边距 - Android
【发布时间】:2020-11-18 14:19:57
【问题描述】:

我喜欢根据条件将边距设置为 TextView。我已经在维度文件中声明了需要根据条件设置的值。

<dimen name="tall">15dp</dimen>
<dimen name="short">5dp</dimen>

在视图 xml 中,我正在尝试设置边距

<TextView
    android:id="@+id/personal_bio"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="@{isTall ? @dimen/tall:@dimen/short}"
    android:singleLine="true"
    android:text="@{viewmodel.personalBio}"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

但是在编译时,这会抛出类似Cannot find a setter for &lt;android.widget.TextView android:layout_marginTop&gt; that accepts parameter type 'float'的错误

类似的条件适用于其他属性,如可见性、颜色和其他少数属性,但无法设置边距。

是否有任何解决方法可以在 xml 本身中实现这一点?

【问题讨论】:

  • 在这种情况下,您可以为此进行自定义绑定,您可以在其中设置边距值动态

标签: android android-layout android-view


【解决方案1】:

尝试使用自定义绑定

class CustomBindings {
companion object {

    @BindingAdapter("setTopMargin")
    @JvmStatic
    fun setTopMargin(view: View, isTall : Boolean){
        getTopMargin(view as TextView,isTall )
    }

    private fun getTopMargin(textView: TextView, isTall : Boolean) {
      if(isTall){
        val typedValue = TypedValue()
        textView.context.resources.getValue(R.dimen.tall, typedValue, true)
        val tall= typedValue.float.toInt()
        
        val param = textView.layoutParams as ViewGroup.MarginLayoutParams
        param.setMargins(0,  tall, 0, 0)
        textView.layoutParams = param
     }else{
        val typedValue = TypedValue()
        textView.context.resources.getValue(R.dimen.small, typedValue, true)
        val small= typedValue.float.toInt()
        
        val param = textView.layoutParams as ViewGroup.MarginLayoutParams
        param.setMargins(0,  small, 0, 0)
        textView.layoutParams = param}
    }
    }

}
}

在xml中

<TextView
android:id="@+id/personal_bio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
setTopMargin="@{isTall}"
android:singleLine="true"
android:text="@{viewmodel.personalBio}"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

【讨论】:

  • 感谢您的解决方案。但是 tall / small 的值始终为 0。因此它不会对布局产生任何影响。
猜你喜欢
  • 2023-04-06
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
相关资源
最近更新 更多