1

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

4 回答 4

0

检查这个_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();
于 2012-07-24T02:47:48.103 回答
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);
于 2012-07-24T05:35:38.653 回答
0

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

于 2012-07-24T05:44:24.033 回答
0

您可以将参数添加到按钮

LinearLayout.LayoutParams lp_l = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
but.setLayoutParams(rel_lp);    
于 2012-07-24T05:05:38.123 回答