使用Kotlin将运行时余量设置为任何视图 [英] Set runtime margin to any view using Kotlin
问题描述
我是Kotlin的初学者.我不太熟悉这种语言.我正在举一个例子,玩代码.我只想将运行时余量设置为任何视图.我也尝试用Google搜索它,但没有为此任务找到任何合适的解决方案.
I am a beginner in Kotlin .I am not too much familier with this language. I am making one example and playing with code. I Just want to set runtime margin to any view. I also trying to google it but not getting any proper solution for this task.
要求
将运行时裕量设置为任何视图.
Set runtime margin to any View.
说明
我获取了一个包含在Button上的xml文件,我想将此按钮的运行时裕度设置为
I have taking one xml file which is contain on Button and I want to set runtime margin to this button.
代码
我也尝试下面的方法,但这是行不通的.
I also try below thing but it's not work.
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
(这是
You need to get the layoutParams
object from button and cast it to ViewGroup.MarginLayoutParams
(which is a parent class of LinearLayout.LayoutParams
, RelativeLayout.LayoutParams
and others and you don't have to check which is btnClickMe
's actual parent) and set margins to whatever you want.
检查以下代码:
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.
希望有帮助.
这篇关于使用Kotlin将运行时余量设置为任何视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!