gpt4 book ai didi

android - 使用 Kotlin 将运行时边距设置为任何 View

转载 作者:IT老高 更新时间:2023-10-28 13:40:57 27 4
gpt4 key购买 nike

我是 Kotlin 的初学者。我对这门语言不太熟悉。我正在制作一个示例并使用代码。我只想将运行时边距设置为任何 View 。我也尝试用谷歌搜索,但没有得到任何合适的解决方案。

要求

将运行时边距设置为任何 View 。

说明

我有一个包含在 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>

我该如何继续?

最佳答案

您需要从按钮获取 layoutParams 对象并将其转换为 ViewGroup.MarginLayoutParams (这是 LinearLayout.LayoutParamsparent class >,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.

希望对你有帮助。

关于android - 使用 Kotlin 将运行时边距设置为任何 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com