您的位置:首页 > 移动开发 > Android开发

add view in code

2016-08-04 11:33 176 查看

标题 ##sample add view in code :

we could be realize it in xml like this :

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:padding="10dp"
android:layout_centerInParent="true"
android:background="@drawable/alert_content_line2" />

<GridView
android:id="@+id/list"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent"
android:numColumns="2" />
</RelativeLayout>


but now we also can realize it with code in java

RelativeLayout relativeLayout = new RelativeLayout(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
View v = new View(context);
v.setBackgroundResource(R.drawable.alert_content_line1);
relativeLayout.addView(v,params);
LayoutParams layoutParams = new LayoutParams(1,-1);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layoutParams.setMargins(0, 10, 0, 10);
v.setLayoutParams(layoutParams);
mGridView = new GridView(context);
mGridView.setNumColumns(2);
relativeLayout.addView(mGridView,params);
LayoutParams layoutParams2 = new LayoutParams(-1,-1);
layoutParams2.setMargins(10, 0, 10, 0);
mGridView.setLayoutParams(layoutParams2);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android