如何以编程方式设置 layout_gravity? [英] How to set layout_gravity programmatically?

查看:28
本文介绍了如何以编程方式设置 layout_gravity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,

如何以编程方式设置我的按钮 layout_gravity?

How to set my buttons layout_gravity programmatically?

我在互联网上找到了这个,但它只是向我抛出一个空指针异常:

I found this on internet, but it simply throws me a Nullpointer exception:

 Button MyButton = new Button(this);

    LinearLayout.LayoutParams  lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
    lllp.gravity=Gravity.RIGHT;
    MyButton.setLayoutParams(lllp); 


    MyLinearLayout.addView(MyButton);

有什么解决办法吗?

推荐答案

Java

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

button.setLayoutParams(params);

科特林

val params = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
    weight = 1.0f
    gravity = Gravity.TOP
}

关于重力值和如何设置重力检查重力.

For gravity values and how to set gravity check Gravity.

基本上,您应该根据父级选择LayoutParams.它可以是 RelativeLayoutLinearLayout 等等...

Basically, you should choose the LayoutParams depending on the parent. It can be RelativeLayout, LinearLayout etc...

这篇关于如何以编程方式设置 layout_gravity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆