第137页
private ImageView iv; //声明一个显示广告图片的ImageView对象
private Handler handler; //声明一个Handler对象
private int[] path = new int[] { R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06 }; //保存广告图片的数组
private String[] title = new String[] { "编程词典系列产品", "高效开发", "快乐分享", "用户人群",
"快速学习", "全方位查询" }; //保存显示标题的数组
(5)在onCreate()方法中,首先获取布局管理器中添加的ImageView组件,然后创建一个新线程,并开启该线程,再实例化一个Handler对象,在重写的handleMessage()方法中,更新UI界面中的ImageView和TextView组件,具体代码如下:
iv = (ImageView) findViewById(R.id.imageView1); //获取显示广告图片的ImageView
Thread t = new Thread(this); //创建新线程
t.start(); //开启线程
//实例化一个Handler对象
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//更新UI
TextView tv = (TextView) findViewById(R.id.textView1); //获取TextView组件
if (msg.what == 0x101) {
tv.setText(msg.getData().getString("title")); //设置标题
iv.setImageResource(path[msg.arg1]); //设置要显示的图片
}
super.handleMessage(msg);
}
};
运行本实例,在屏幕上将每隔两秒钟随机显示一张广告图片,如图12.8所示。
图12.8 电子广告牌
12.3 经典范例
12.3.1 多彩的霓虹灯
例12.6 在Eclipse中创建Android项目,名称为12.6,实现多彩霓虹灯。(实例位置:光盘\TM\sl\ 12\12.6)
(1)修改新建项目的res\layout目录下的布局文件main.xml,将默认添加的TextView组件删除,并为默认添加的线性布局管理器设置ID属性,具体代码请参见光盘。
(2)在res/values目录下,创建一个保存颜色资源的colors.xml文件,在该文件中,定义7个颜色资源,名称依次为color1、color2、…、color7,颜色值分别对应赤、橙、黄、绿、青、蓝、紫。colors.xml文件的关键代码如下:
#ffff0000
#ffff6600
#ffffff00
#ff00ff00
#ff00ffff
#ff0000ff
#ff6600ff
(3)在该MainActivity中,声明程序中所需的成员变量,具体代码如下:
private Handler handler; //创建Handler对象
private static LinearLayout linearLayout; //整体布局
public static TextView[] tv = new TextView[14]; //TextView数组
int[] bgColor=new int[]{R.color.color1,R.color.color2,R.color.color3,
R.color.color4,R.color.color5,R.color.color6,R.color.color7}; //使用颜色资源
private int index=0; //当前颜色值
(4)在MainActivity的onCreate()方法中,首先获取线性布局管理器,然后获取屏幕的高度,接下来再通过一个for循环创建14个文本框组件,并添加到线性布局管理器中,具体代码如下:
linearLayout=(LinearLayout)findViewById(R.id.ll); //获取线性布局管理器
int height=this.getResources().getDisplayMetrics().heightPixels; //获取屏幕的高度
for(int i=0;i
tv[i]=new TextView(this); //创建一个文本框对象
tv[i].setWidth(this.getResources().getDisplayMetrics().widthPixels); //设置文本框的宽度
tv[i].setHeight(height/tv.length); //设置文本框的高度
linearLayout.addView(tv[i]); //将TextView组件添加到线性布局管理器中
}
(5)创建并开启一个新线程,在重写的run()方法中实现一个循环,在该循环中,首先获取一个Message对象,并为其设置一个消息标识,然后发送消息,最后让线程休眠1秒钟,具体代码如下:
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message m = handler.obtainMessage(); //获取一个Message
m.what=0x101; //设置消息标识
handler.sendMessage(m); //发送消息
try {
Thread.sleep(new Random().nextInt(1000)); //休眠1秒钟