使用 Kotlin 为任何视图设置运行时边距

问题描述 投票:0回答:6

我是 Kotlin 的初学者。我对这门语言不太熟悉。我正在制作一个例子并使用代码。我只想为任何视图设置运行时裕度。我也尝试用谷歌搜索它,但没有找到任何适合此任务的解决方案。

要求

为任何视图设置运行时边距。

描述

我有一个包含在 Button 上的 xml 文件,我想为此按钮设置运行时边距。

代码

我也尝试了下面的方法,但它不起作用。

class MainActivity : AppCompatActivity() {


//private lateinit var btnClickMe: Button
//var btnClickMe=Button();

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //For setting runtime text to any view.
        btnClickMe.text = "Chirag"

        //For getting runtime text to any view
        var str: String = btnClickMe.text as String;

        //For setting runtimer drawable
       btnClickMe.background=ContextCompat.getDrawable(this,R.drawable.abc_ab_share_pack_mtrl_alpha)//this.getDrawable(R.drawable.abc_ab_share_pack_mtrl_alpha)


        /*
        //For Setting Runtime Margine to any view.
        var param:GridLayout.LayoutParams
        param.setMargins(10,10,10,10);

        btnClickMe.left=10;
        btnClickMe.right=10;
        btnClickMe.top=10;
        btnClickMe.bottom=10;
        */

        // Set OnClick Listener.
        btnClickMe.setOnClickListener {
            Toast.makeText(this,str,5000).show();
        }

    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
tools:context="chirag.iblazing.com.stackoverflowapp.MainActivity"
android:layout_height="match_parent">

<Button
    android:id="@+id/btnClickMe"
    android:text="Click Me"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

我该如何继续?

android button kotlin
6个回答
115
投票

您需要从按钮获取

layoutParams
对象并将其强制转换为
ViewGroup.MarginLayoutParams
(这是 LinearLayout.LayoutParams
RelativeLayout.LayoutParams
等的
父类
,并且您不必检查哪个是
btnClickMe
)的实际父级)并将边距设置为您想要的任何内容。

检查以下代码:

val param = btnClickMe.layoutParams as ViewGroup.MarginLayoutParams
param.setMargins(10,10,10,10)
btnClickMe.layoutParams = param // Tested!! - You need this line for the params to be applied.

55
投票

这就是我想在 Kotlin 中做的事情 -

fun View.margin(left: Float? = null, top: Float? = null, right: Float? = null, bottom: Float? = null) {
    layoutParams<ViewGroup.MarginLayoutParams> {
        left?.run { leftMargin = dpToPx(this) }
        top?.run { topMargin = dpToPx(this) }
        right?.run { rightMargin = dpToPx(this) }
        bottom?.run { bottomMargin = dpToPx(this) }
    }
}

inline fun <reified T : ViewGroup.LayoutParams> View.layoutParams(block: T.() -> Unit) {
    if (layoutParams is T) block(layoutParams as T)
}

fun View.dpToPx(dp: Float): Int = context.dpToPx(dp)
fun Context.dpToPx(dp: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt()

现在我们只需在类似

的视图上调用它即可
textView.margin(left = 16F)

9
投票

这里有一个有用的 Kotlin 扩展方法:

fun View.setMargins(
    left: Int = this.marginLeft,
    top: Int = this.marginTop,
    right: Int = this.marginRight,
    bottom: Int = this.marginBottom,
) {
    layoutParams = (layoutParams as ViewGroup.MarginLayoutParams).apply {
        setMargins(left, top, right, bottom)
    }
}

像这样使用它:

myView.setMargins(
   top = someOtherView.height
   bottom = anotherView.height
)

编辑:解决方案类似于 Hitesh 的答案,但我使用的是(原始)

ViewGroup.setMargins
(以像素为单位)。当然,您可以根据这些示例制作自己的
setMarginsDp
变体,或者在调用我的实现之前使用 Hitesh 的
dpToPx
扩展。您选择哪种解决方案取决于您自己的口味。

另请注意,我的解决方案(重新)设置了所有边距,尽管在大多数情况下这不会成为问题。


1
投票

这是 CardView

的另一个示例
            myCardView.elevation = 0F
            myCardView.radius = 0F
            val param = (myCardView.layoutParams as ViewGroup.MarginLayoutParams).apply {
                setMargins(0,0,0,0)
            }
            myCardView.layoutParams = param

1
投票

如果您想更改特定边距(例如顶部或底部),您可以使用以下代码与数据绑定。

 @BindingAdapter("android:layout_marginTop")
        @JvmStatic
        fun setLayoutMarginTop(view: View, marginTop: Float) {
            val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
            layoutParams.topMargin = marginTop.toInt()
            view.layoutParams = layoutParams
        }

在 .xml 文件中,您可以像下面的代码那样编写

 <ImageView
        android:id="@+id/imageView3"
        android:layout_width="@dimen/_15dp"
        android:layout_height="@dimen/_15dp"
        android:layout_marginTop="@{homeViewModel.getLanguage() ? @dimen/_14dp : @dimen/_32dp }"
        android:contentDescription="@string/health_indicator"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView1"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        android:src="@{ homeViewModel.remoteStatusVisible ? @drawable/green_rectangle : @drawable/gray_rectangle}"/>

0
投票

如果您只想以编程方式将右边距设置为 0

val params: ViewGroup.MarginLayoutParams =
                  yourView!!.layoutParams as ViewGroup.MarginLayoutParams
params.rightMargin = 0  // 
binding.progressParent.layoutParams = params
© www.soinside.com 2019 - 2024. All rights reserved.