Android界面动态生成View

代码在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是相对应的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值