实时改变Toast提示信息-Handler的使用

       实时改变Toast提示信息,实现功能:运行该软件时,后台自动启动线程,每一秒钟发送一次消息,在手机屏幕上会显示出需要提示的信息,当发到10条时,系统停止发送消息。

     该程序主要运用到了Handler接收消息的功能,在这里需要说明的是Handler和Thread不一定是对应的,也就是说在一个线程中可以有多个Handler,每个消息都可以指定不同的Handler,因为每个消息都可以有不同的行为。


   下面首先给出布局文件;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.toasttdw.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过有消息循环的线程定时显示Toast" 
        android:layout_centerInParent="true"/>

</RelativeLayout>

布局文件中只有一个TextView控件。只是起到一个背景作用。

接下给出主要功能代码,

package com.example.toasthh;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class MainActivity extends Activity {

	private int count = 0;
	Handler handler = new Handler(){
		
		@Override
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(MainActivity.this, "计时器值:"+msg.what, Toast.LENGTH_SHORT).show();
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(1*1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(count == 10){
						break;
					}
					handler.sendEmptyMessage(count++);
				}				
			}
		}).start();
	}
}

在主线程中启动一个线程,每隔一秒发送发送消息,在handleMessage(android.os.Message msg)接收消息并且Toast显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值