Home
JavaEE
Java GUI
Framework
DHtml
Android
插画
留言本
  • 我和老婆的婚纱相,自已做成了web方式
  • Java下实现XP强制关机的方法
  • 对暴力破解带密码的QQ相册的可行性分析
  • 今晚在163上看到新闻,但最令我感概的是该项新闻的评论
  • windows下安装CodeBlocks+MinGW+wxWidgets的方法
  • Android中给Spinner或ListView添加数据
  • 我用android sdk做的一个扫雷游戏
  • 看看android扫雷游戏的主要代码
  • 哈哈,老婆怀上了!婚礼不变,还是在正月十二!
  • Android中,Drawable接口及其子类的使用方法
  • 在客户端IE中使用jasperView,客户端显示JasperViewer
  • jspsmartupload取得参数的值是乱码的问题
  • 客户端显示JasperViewer并在Jasperview的applet中加超链接
  • Hibernate基于链接表的多对多many-to-many双向关联例子
  • Hibernate双主键的设置例子
  • Hibernate中的properties和formula的用法
  • Android中,Drawable接口及其子类的使用方法
  • Android中用Bitmap获取图片中某个区域的图象
  • Android中AnimationDrawable实现简单动画的例子
  • Animation与Interpolator及AnimationSet的用法
在android的sdk中动态添加view的方法
posted by David Chen at May 6, 2009, 5:22 PM

在android的sdk中,可以通过layout的XML来定议面板中的布局及布局中的可视对象,但一般情况下,
必须要有动态生成可视对象关添加到面板中的情况,而且在需要overwrite一些方法的时候,也是必须要用到
动态的,不能在XML中指定这些动态对象。

1) 获取固定在xml中的对象比较简单,只需调用Activity的findViewById方法就行了,前提是该固
定对象在xml中必须要有一个id的属性。
public View findViewById(int id);
Finds a view that was identified by the id attribute from the XML that was processed
in onCreate(Bundle).
returns The view if found or null otherwise.
// 返回一个在XML中定义了id属性的可视对象,注意,Layout也是View的一种,也是可以通过findViewById取得。

2) 动态生成view对象
如下代码:
public class T2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// 取得活动面板的布局,因为android所有的面板布局都是View的子类
final LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01);
// 如果在xml中没有这个布局的id,要去手动添加,然后就可以用findViewById取得
final TextView tv = (TextView) findViewById(R.id.TextView01);
// 动态添加对象
/* widget 的构造函数中的Context参数就是当前的Activity */
final Button bn = new Button(this) {
// 重写按纽的onKeyUp函数
public boolean onKeyUp(int key, KeyEvent e) {
tv.setText("key: " + key);
return true;
}
};
bn.setText("C1");
// 创建对象后,必须加到面板上,可以用相应的面板布局的LayoutParams来控制布局
//LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-2, -2);
layout.addView(bn);

}
}
Labels:   Java    Android  
Trackback:   http://cwq.iou1314.com/android-view_a348
本站内的任何文章,只代表个人意见或学习所用,如有版权声明,请尊重作者的劳动成果,在转载时请保留原始链接并注明出处。
© 2007 - 2010 CWQ.IOU1314.COM All Rights Reserved.