如何在android中添加组件到当前视图

时间:2011-09-12 15:00:52

标签: android android-layout android-widget

我是android的新手,只是想修改一个基本的例子。

main.xml就像

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<Button android:layout_width="228dp" android:layout_height="wrap_content" android:id="@+id/addButton" android:text="@string/addBtn"></Button>
 </LinearLayout>

想要点击按钮添加TextField。如何添加Child才能查看?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btn=(Button)findViewById(R.id.addButton);
    btn.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    EditText editText = new EditText(v.getContext());
    //Append the editText to View

}

如何将其附加到当前视图/布局?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

这样的事情对我有所帮助。

ParentView.post(new Runnable() {
                    public void run() {
                        ParentView.addView(newView,0);
                        LinearLayout.LayoutParams rlparams = (LinearLayout.LayoutParams)rldeal.getLayoutParams();
                        rlparams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                        rlparams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                        newView.setLayoutParams(rlparams);
                    }
                });