2013-07-03 60 views
0

我有一個單一的TextView的XML佈局靜態和動態佈局可能嗎?

現在我想添加50個按鈕,我想在我的java文件中動態添加!

是否可以通過java代碼將屬性添加到XML文件? 或者一次活動可以同時有2個佈局?

用於例如,

public class Options extends Activity 
{ 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.options); 
    Button but=new Button(this); 
    but.setText("Wassup"); 
    // How do I add this button to the layout ? 
} 

} 
+0

看到這個... http:// stackoverflow。com/questions/5631913/add-a-button-dynamic-to-a-linelayout-in-android 可能是重複的。 –

回答

3

是否可以通過java代碼將屬性添加到XML文件?

沒有,但您可以根據與setText()做添加屬性ViewsLayouts。編譯後,resource文件本身無法更改。

或者一個活動一次可以有2個佈局嗎?

簡單的答案是否定的,但你可以inflate另一個佈局,並將其添加到當前佈局。

你可以做添加Button

充氣根layoutaddView()添加Buttons什麼變化例。像

Layoutinflater inflater = (LayoutInflater) getSystemService 
    (Context.LAYOUT_INFLATER_SERVICE); 
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout_file); 
Button but=new Button(this); 
but.setText("Wassup"); 
// How do I add this button to the layout ? 
ll.addView(but); 

LayoutInflater

或者,如果你想它在當前文件添加到layout你可以使用findViewById()和使用上addView()東西添加到Buttons

+0

非常感謝:) – Vaido

+0

非常歡迎 – codeMagic

0

是的,它是可能的。 setContentView(R.layout.options);findViewById()後得到你的按鈕容器。你將有一個LinearLayout,RelativeLayout或其他的參考。之後,使用佈局充氣器和編程方式,您可以添加其他佈局或組件。

希望它能幫助!

+0

我會建議你也許給他一個編碼的例子。 – yams

+0

@MarkBasler我在我的個人資料中寫道:我不給魚,我很想教一個小小的捕魚。我知道這會是一個好消息,但用他的大腦和谷歌。 OFc,如果他是支付我會寫代碼:) – 2013-07-03 16:44:56

+0

注意接受的答案有一個例子。它並不需要完全符合他們的需求。 – yams

0

只需使用layout.addView()式佈局是通過調用findViewById(R.id.layoutId)得到的ViewGroup

1

考慮到你有如下一個XML佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@id/mainlayout" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" > 
</TextView> 

</LinearLayout> 

在setContentView(R.layout.options)之後的Java代碼;您可以執行以下操作:

LinearLayout linearLayout=(LinearLayout)findViewById(R.id.mainlayout); 
Button button=new Button(this); 
linearLayout.addView(button); 

現在,您可以在線性佈局中添加儘可能多的按鈕,如上所示。