动态添加视图时,如何确定LayoutParams的类型

来源:互联网 发布:计算机编程好学么 编辑:程序博客网 时间:2024/05/29 04:55

在使用addView(View child, LayoutParams params)动态增加view视图时,其中第二个参数为LayoutParams params。该LayoutParams可定义为不同的类型,包括LinearLayout,RelativeLayout,FrameLayout等,到底采用哪种类型的布局方式呢?这要看谁调用了addView这个方法,举个例子:

LinearLayout ll_layout = (LinearLayout)findViewById(R.id.ll_layout);
ll_layout.addView(View child, LayoutParams params);

那么上面这个params定义为何种类型的LayoutParams呢?
因为ll_layout是LinearLayout 类型,因此params应该如下创建:

LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(100, 50,
80, 100);

上面相当于child这个子类在xml的布局为如下定义:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/ll_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:descendantFocusability="blocksDescendants"    android:orientation="horizontal"     android:background="#ffffff">    <TextView        android:id="@+id/text_view"        android:layout_width="wrap_content"        android:layout_height="50dp"        android:layout_centerVertical="true"        android:gravity="left|center_vertical"        android:textColor="#000" /><!--该Button为上面的child子类-->    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginBottom="100dp"        android:layout_marginLeft="100dp"        android:layout_marginRight="80dp"        android:layout_marginTop="50dp" /></LinearLayout>
0 0
原创粉丝点击