如何设置layout_gravity programmaticaly?如何设置、layout_gravity、programmaticaly

2023-09-12 04:00:03 作者:爺是屌絲爺怕誰

如何设置layout_gravity编程的按钮?

我发现这个例子在互联网上,但它只是抛出了我一个空指针异常:

 按钮用作MyButton =新的按钮(这一点);

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


    MyLinearLayout.addView(用作MyButton);
 

解决方案

  LinearLayout.LayoutParams PARAMS =新LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);
params.weight = 1.0F;
params.gravity = Gravity.TOP;

button.setLayoutParams(PARAMS);
 

有关重力值,以及如何设置重力检查重力

LinearLayout中gravity与 layout gravity 移动开发 weixin 44696542的博客 CSDN博客

How to set layout_gravity programatically for buttons?

I found this example on internet, but its 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);

解决方案

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

button.setLayoutParams(params);

For gravity values and how to set gravity check Gravity