动态添加一个view。
首先,搞清楚是哪个view(子view),要添加到哪个view(父view)中;其次,子view的属性怎么设置;这两个问题明白了,就容易了。
举个例子:比如要在一个LinearLayout中添加一个Button, 子view是Button,父view是LinearLayout。 子view的属性就是通过LayoutParams来设置的,注意是LinearLayout.LayoutParams,因为子view的高度,宽度这些都是针对父view的,要告诉父view自己要占用多大空间,所以是LinearLayout(原来总是会用子view的LayoutParams来设置,错误)
public class MyActivity extends Activity { private Context mContext; private LinearLayout mLinearLayout; private LinearLayout.LayoutParams mLayoutParams; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mContext = this; mLinearLayout = (LinearLayout)findViewById(R.id.parent_view); mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); Button button = new Button(mContext); button.setText("添加button"); mLinearLayout.addView(button, mLayoutParams); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:id="@+id/parent_view" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-03 22:25:35