繁体   English   中英

如何在Android中以编程方式调整按钮的大小

[英]How to resize the button progmmatically in android

我希望Ui以编程方式完成,我正在使用简单的按钮,它占用了屏幕的整个宽度,我应该如何调整按钮的宽度。

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    TextView label = new TextView(this);  
    label.setText("Hello");  
    label.setTextSize(20);  
    Button but = new Button(this);

    but.setText("Click Me");
    but.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            System.out.println("Button Clicked");
            Intent myIntent = new Intent(v.getContext(), SecondActivity.class);
            startActivityForResult(myIntent, 0);
        }
    });
    LinearLayout ll = new LinearLayout(this);  
    ll.setOrientation(LinearLayout.VERTICAL);  

    ll.addView(label);
    ll.addView(but);
    setContentView(ll);  

}

我应该向该按钮添加任何单独的布局吗?有关以编程方式加深对布局的理解的任何教程都将很有用。

此致Rakesh Shankar.P

Resize Button programmatically using Java Code检查 Resize Button programmatically using Java Code

                                   (or)

final float scale = getResources().getDisplayMetrics().density;
int heightDp = (int) (33 * scale + 0.5f);
ViewGroup.LayoutParams params = b.getLayoutParams();//b========>ur button
params.height = heightDp;
b.setLayoutParams(params);
b.requestLayout();

您可以向按钮添加参数

LinearLayout.LayoutParams lp_l = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
but.setLayoutParams(rel_lp);    
LayoutParams params =new      LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

Button btn = new Button(this);
btn.setText("login");
btn.setLayoutParams(params);

layout.addView(btn);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM