使用Kotlin为任何视图设置运行时余量

ryoqjall  于 2022-12-27  发布在  Kotlin
关注(0)|答案(5)|浏览(133)

我是一个初学者在Kotlin。我不是太熟悉这种语言。我正在做一个例子,玩代码。我只是想设置运行时余量的任何看法。我也试图谷歌它,但没有得到任何适当的解决方案,这项任务。

    • 要求**

设置任意视图的运行时余量。

    • 说明**

我已经采取了一个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();
        }

    }

}
    • 活动_主要. 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>

我该如何继续?

8tntrjer

8tntrjer1#

您需要从button获取layoutParams对象,并将其强制转换为ViewGroup.MarginLayoutParamsLinearLayout.LayoutParamsRelativeLayout.LayoutParams和其他对象的parent class,您不必检查哪个是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.
5ssjco0h

5ssjco0h2#

我想在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)
xv8emn3q

xv8emn3q3#

下面是一个有用的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
)

EDIT:解决方案类似于the answer from Hitesh,但我使用的是(原始的)ViewGroup.setMargins,以像素为单位,当然你可以根据这些例子制作自己的setMarginsDp变体,或者在调用我的实现之前使用Hitesh的dpToPx扩展,选择哪种解决方案取决于你自己的口味。
还要注意,我的解决方案(重新)设置了所有边距,尽管在大多数情况下这不是问题。

hpcdzsge

hpcdzsge4#

如果你想改变特定的边距,如顶部或底部,你可以使用下面的代码与数据绑定。

@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}"/>
fquxozlt

fquxozlt5#

下面是CardView的另一个示例

myCardView.elevation = 0F
            myCardView.radius = 0F
            val param = (myCardView.layoutParams as ViewGroup.MarginLayoutParams).apply {
                setMargins(0,0,0,0)
            }
            myCardView.layoutParams = param

相关问题