android viewGroup中addView使用方式及其粗解

原文:http://write.blog.csdn.net/postedit/50562162

addView是继承viewGroup的方法,

void android.view.ViewGroup.addView(View child);

void android.view.ViewGroup.addView(View child, LayoutParams params);

void android.view.ViewGroup.addView(View child,int index, LayoutParams params);


其中需要注意的是 index ,在linearlayout中使用addView的时候,如果linearlayout方向是vertical 垂直, index代表添加的child的view在linearlayout的行数,index是0,表示添加的child在linearlayout顶部,-1为底部。位置可随意调整。


如下demo:


常见使用方式:

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

LinearLayout relativeLayout = (LinearLayout)findViewById(R.id.test2);
     View container = LayoutInflater.from(this).inflate(R.layout.add_content, null);
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
     relativeLayout.addView(container, 0, params);

// relativeLayout.addView(container, -1, params);

//relativeLayout.addView(container, 1, params);

//relativeLayout.addView(container, 2, params);

}


activity_main.xml:

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

            android:id="@+id/test2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical" >

                    android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:background="@android:color/background_light"
            android:layout_alignParentTop="true"
            android:text="2222222222" />
                    android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_below="@id/tv1"
            android:background="@android:color/black"
            android:text="333333333333333" />
   

            android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


add_content.xml:

      xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

            android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@android:color/white"
        android:text="11111TextView111111" />

原文:http://write.blog.csdn.net/postedit/50562162




你可能感兴趣的:(android viewGroup中addView使用方式及其粗解)