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

时间:2012-07-24 02:19:06

标签: android android-layout

我希望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

4 个答案:

答案 0 :(得分:0)

检查this 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();

答案 1 :(得分:0)

您可以将params添加到按钮

LinearLayout.LayoutParams lp_l = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
but.setLayoutParams(rel_lp);    

答案 2 :(得分:0)

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);

答案 3 :(得分:0)

请以编程方式查看此链接以调整大小按钮http://android-coding.blogspot.in/2011/05/resize-button-programmatically-using.html