代码在onCreate方法中实现。
1、创建一个View(本文为Button)实例:
java代码:
Button button=new Button(this);//创建Button
button.setId(100);//设置Button的ID
button.setBackgroundColor(Color.RED);//设置Button的背景色
button.setText("Hello World");//设置Button的文字
//设备Button的尺寸及位置信息
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(100,100); //创建Layoutparams实例,参数是宽及高,单位px。
params.addRule(RelativeLayout.CENTER_IN_PARENT);//设置位置信息
button.setLayoutParams(params);//应用Layoutparams实例到View
设置Button的尺寸也可用setHeight,setWidth方法,或者:
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LayoutParams的addRules有两个方法:addRule(int verb)及addRule(int verb, int anchor) ,verb参数有两类,一类是不要相对view的,如ALIGN_WITH_PARENT_BOTTOM等,一种是要相对view的,如above,right_of等,anchor是相对view的id。
2、把View加入要显示的界面:
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.miko.zd.dynamicview.MainActivity"
android:id="@+id/relative">
</RelativeLayout>
java代码:
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null);//返回布局文件最外层View容器RelativeLayout,RelativeLayout继承于ViewGroup。
viewGroup.addView(button);//Button添加到RelativeLayout中
setContentView(viewGroup);//为Activity绑定显示的布局
也可通过FindViewByID返回最外层的View:
View viewGroup = findViewById(R.id.relative);
setContentView()一旦调用,layout就会立刻显示UI,而后的findViewById找到RelativeLayout实际上已经加载出来了,添加Button,可以理解为显示出UI后动态的添加View;inflate只会把Layout形成一个以view类实现的对象,有需要时再用setContentView(view)显示出来。
只有RelativeLayout.layoutParam具有addRules方法,这与XML是相对应的。