2012-08-28 28 views
2

我已經以編程方式通過以下方法創建按鈕:編程調整按鈕

Button button = new Button(this); 
    button.setText("Previous"); 
    setContentView(button); 

我越來越按鈕,但全屏幕所佔據。如何調整它並根據我的需要放置它?

回答

2

在你onCreate方法:

LinearLayout layout=new LinearLayout(this); 

       Button button = new Button(this); 
       button.setText("Previous"); 
       button.setLayoutParams(new LayoutParams(
         LayoutParams.WRAP_CONTENT, 
          LayoutParams.WRAP_CONTENT)); 
       layout.setOrientation(LinearLayout.VERTICAL); 
       layout.addView(button); 
       setContentView(layout); 
1

全屏佔用,因爲你setContentViewbutton

如果你想要做的是調整大小Viewandroid。使用LayoutParams。例如:

button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

這樣做會調整按鈕的大小以適合文本"Previous"

OK,你可以試試這個tutorial.

+0

u能幫助如何使用它?直接它不工作.. –

+0

你有'activity_main.xml'嗎?如果是,那麼在那裏設置你的觀點。並將'button'添加到[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html) – Aprian

+0

爲您添加了一個基本的android佈局教程鏈接。 – Aprian