广告牌android开发,Android开启新线程实现电子广告牌项目

利用之前学过的多线程处理技术,我们做一个开启新线程实现电子广告牌的项目

界面布局文件,加入ImageView图片控件,用于显示一个图片,一个TextView控件,用于显示广告说明语。

res/layout/main.xml:

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/linearLayout1"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="10dp"

android:src="@drawable/hint"/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="10dp"/>

在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();//输出异常信息

}

}

}

}

显示效果如图

3b385c256cd4f3e3a4d379a3ca795930.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值