在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);
}
}