我只是想動態地將按鈕添加到我的佈局,當我想。 的按鈕應該是這樣的XML按鈕:如何以編程方式創建按鈕?
<Button android:text="Text"
android:gravity="bottom"
android:textSize="10dp"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:background="@drawable/attack1"
android:layout_height="wrap_content"
android:id="@+id/workingButton">
</Button>
。
public class GravityIssueActivity extends Activity
{
LinearLayout layout;
Button newButton;
Button buttonByXml;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//the button in the xml file
buttonByXml = (Button)findViewById(R.id.workingButton);
layout = (LinearLayout)findViewById(R.id.layoutToInsert);
//my new programatically "born" button
newButton = new Button(this);
//Setting the properties as i want
newButton.setText("Text");
newButton.setTextSize(10);
newButton.setTextColor(Color.WHITE);
newButton.setBackgroundResource(R.drawable.attack1);
// Gravity = Bottom !!!!!!!!!!
newButton.setGravity(Gravity.BOTTOM);
// getting the XML buttons params just for case...
newButton.setLayoutParams(new LayoutParams(buttonByXml.getLayoutParams()));
//Adding my new Button to the layout
layout.addView(newButton);
}
}
這裏是結果的圖像:
這怎麼可能成爲不同的結果,當我複製所有的屬性?
說實話,我只得到了重力問題。我無法讓文字處於最底層。 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams \t(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT); params.gravity = 80只是不工作, –
你需要重力來對齊按鈕內的文本或對齊它的父母內的按鈕? – Vladimir
我只是想按鈕的文本對齊按鈕的底部:) –