利用之前学过的多线程处理技术,我们做一个开启新线程实现电子广告牌的项目
界面布局文件,加入ImageView图片控件,用于显示一个图片,一个TextView控件,用于显示广告说明语。
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:src="@drawable/hint"/> <TextView android:id="@+id/TextView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp"/> </LinearLayout>
在res/drawable下加入几张广告图片(ad1.jpg、ad2.jpg、ad3.jpg、ad4.jpg、ad5.jpg)
在主界面中,产生随机数不断的变换在ImageView空间上的图片资源文件,来实现一个类似于幻灯片的电子广告牌
MainActivity:
package com.example.test;    import java.util.Random;   import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ImageView; import android.widget.TextView;   public class MainActivity extends Activity implements Runnable{     private ImageView imageView;    private TextView textView;    private Handler handler;    private int[] path=new int[]{R.drawable.ad1,R.drawable.ad2,        R.drawable.ad3,R.drawable.ad4,R.drawable.ad5};    private String[] title=new String[]{"美国进口葡萄酒","乐享移动4G时代",        "江山御景楼盘开售","大学康城新区现房","五粮液精品"};   @Override    public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.main);          imageView=(ImageView)findViewById(R.id.imageView1);     textView=(TextView)findViewById(R.id.TextView1);          Thread t=new Thread(this);//创建新线程     t.start();//开启线程     //实例化一个Handler对象     handler=new Handler(){         @Override       public void handleMessage(Message msg) {         //更新UI         if(msg.what==0x101){           textView.setText(msg.getData().getString("title"));//设置标题           imageView.setImageResource(path[msg.arg1]);//设置要显示的图片         }         super.handleMessage(msg);       }            };   }   /*    * 判断当前线程是否被中断,如果没有被中断,    * 则首先产生一个随机数,然后获取一个Message,并将要显示    * 的广告图片的索引值和对应标题保存到该Message中,再发生    * 消息,最后让线程休眠2秒钟    * */   @Override   public void run() {     int index=0;     while(!Thread.currentThread().isInterrupted()){       index=new Random().nextInt(path.length);//产生一个随机数       Message m=handler.obtainMessage();//获取一个Message       m.arg1=index;//保存要显示广告图片的索引值       Bundle bundle=new Bundle();//获取Bundle对象       m.what=0x101;//设置消息标识       bundle.putString("title",title[index]);//保存标题       m.setData(bundle);//将Bundle对象保存到Message中       handler.sendMessage(m);//发送消息       try {         Thread.sleep(2000);//让线程休眠2秒钟       } catch (InterruptedException e) {         // TODO Auto-generated catch block         e.printStackTrace();//输出异常信息       }     }   }   } 显示效果如图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。
新闻热点
疑难解答