2013-12-17 56 views
0

所以我只爲按鈕創建了XML佈局。將動態按鈕佈局設置爲不帶ID的XML文件?

buttons.xml

<?xml version="1.0" encoding="utf-8"?> 
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="35dp" 
    android:layout_height="35dp" 
    android:layout_marginLeft="5dp" 
    android:layout_marginRight="5dp" 
    android:background="@drawable/b1" > 
</Button> 

main.java

public void addButton() { 
    Button btn=new Button(this); 
} 

因此如何設置buttons.xml佈局,而無需使用ID來BTN?

+0

使用充氣器。 – njzk2

+0

當我使用 按鈕btn =(按鈕)LayoutInflater.from(this).inflate(R.layout.buttons,null); 所以它劑量數學高度和寬度在XML文件! –

回答

1

你可以這樣做:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:utilidades="http://schemas.android.com/apk/res/com.movidromo.ifilmfest" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/buttonContainer"> 
</LinearLayout > 

而在你的代碼,你可以添加到這個線性佈局的按鈕,其屬性:

Button yourNewButton = new Button (getBaseContext()); 
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT); 
lparams.setMargins(0, 0, 0, 0); 
yourNewButton.setLayoutParams(lparams); 
yourNewButton.setPadding(0, 0, 0, 0); 
yourNewButton.setGravity(Gravity.CENTER); 
yourNewButton.setBackgroundResource(R.drawable.yourBackground); 
LinearLayout layButtons = (LinearLayout) findViewById(R.id.buttonContainer); 
layButtons.addView(yourNewButton); 
0

編程可以設置HeightWidth

佈局custom_button.xml

<?xml version="1.0" encoding="utf-8"?> 
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="50dp" 
    android:drawablePadding="5dp" 
    android:background="@android:color/transparent" 
    android:gravity="center" 
    android:singleLine="true"> 
</Button> 

在代碼

private void createView() { 
    btn = (Button)(context.getLayoutInflater().inflate(R.layout.custom_button, null)); 
    btn.setCompoundDrawablesWithIntrinsicBounds(0, iconId, 0, 0); 
    btn.setText(btnText); 
    btn.setTextColor(btnTextColor); 
    btn.setTextSize(btnTextSize); 
    btn.setBackgroundDrawable(btnBackGrad); 
    btn.setMinimumHeight(50); 
    btn.setWidth(50); 
    btn.setPadding(0, 5, 0, 0); 
} 

我希望這能幫助你。