簡體   English   中英

在Android中將動態布局添加到XML

[英]Add dynamic layout to xml in android

我的主要活動代碼是:

<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/Container"> </LinearLayout>

我的動態布局代碼是:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView sv = new ScrollView(this);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);


    TextView tv = new TextView(this);
    tv.setText("Dynamic layouts ftw!");
    ll.addView(tv);

    EditText et = new EditText(this);
    et.setText("weeeeeeeeeee~!");
    ll.addView(et);

    Button b = new Button(this);
    b.setText("I don't do anything, but I was added dynamically. :)");
    ll.addView(b);

    for(int i = 0; i < 20; i++) {
        CheckBox cb = new CheckBox(this);
        cb.setText("I'm dynamic!");
        ll.addView(cb);
    }
    this.setContentView(sv);
}

我想在帶有ID = Container的LinearLayout中添加動態編碼的View。 怎么做

this.setContentView(sv);

用。。。來代替:

setContentView(R.layout.<layout_name>);

ViewGroup container = (ViewGroup)findViewById(R.id.Container);
container.addView(sv);

我看到您沒有設置任何布局參數。 您可能想要這樣做。

 LinearLayout linearlayoutinxml = (LinearLayout)findViewById(R.id.Container); 
 // then you add your custom view
 linearlayoutinxml.addView(sv);
 setContentView(linearlayoutinxml);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM