在已有布局中动态添加控件

转自: http://blog.csdn.net/andypan1314/article/details/7306395

             http://blog.csdn.net/dany1202/article/details/5912213

*****************************************************************************************

  1. //手动添加imageview  
  2.         RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relaGameZhaiGuoZi);  
  3.         imgApple2 = new ImageView(this);  
  4.         imgApple2.setImageResource(R.drawable.app);  
  5.         imgApple2.setId(110);   //注意这点 设置id  
  6.         imgApple2.setOnClickListener(this);  
  7.         RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
  8. //        lp1.addRule(RelativeLayout.ALIGN_TOP);  
  9. //        lp1.setMargins(30, 50, 100, 100);//(int left, int top, int right, int bottom)  
  10.         lp1.leftMargin=30;  
  11.         lp1.topMargin = 100;  
  12.         mainLayout.addView(imgApple2,lp1);  


首先获取要添加于哪的容器,然后通过

RelativeLayout.LayoutParams对象的相关属性,设置该控件在相对布局中的位置,有3种设置方法,正如上面注释的地方所示,特别注意的是设置id(imgApple2.setId(110);),方便在以后onclick监听事件中进行对应的处理。

*****************************************************************************************

将想要显示隐藏的所有控件放到一个面板layout上,定义该面板id。

<RelativeLayout android:id="@+id/layout_effect"

  。。。

  。。。>

</RealtiveLayout>


在java代码中定义该控件

RelativeLayout layout=(RelativeLayout)findViewById(R.id.layout_effect);   

 

layout.setVisibility(View.INVISIBLE);         控制该控件面板layout不可见,但是他依旧占用空间。比如用linerlayout进行布局,设置这个属性后,此位置按键不可见,但下一个按键不会占用它的位置。

 

findViewById(R.id.layout_effect).setVisibility(View.GONE);       控制该控件面板消失。比如用linerlayout进行布局,设置这个属性后,相当于这里没有这个布局,下一个按键会向前移动,占用此控件的位置。

 xml文件

android:visibility="invisible"


*****************************************************************************************

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值