• android之消息机制(二)


    消息通道:Looper

    首先编写main.xml文件

    代码如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    	<TextView 
    	    android:id="@+id/info"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"/>
    	<Button 
    	    android:id="@+id/but"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:text="启动"/>
    </LinearLayout>
     
    

      然后改写Activity.java类

    代码如下:

    package com.example.myfirstproject;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    import android.app.Activity;
    import android.content.pm.ActivityInfo;
    import android.content.res.Configuration;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.*;
    
    public class MainActivity extends Activity {
    	private TextView info;
    	private Button but;
    	private static final int SET = 1;
    	
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.info = (TextView)super.findViewById(R.id.info);
            this.but = (Button)super.findViewById(R.id.but);
            this.but.setOnClickListener(new OnClickListenerlmpl());
        }    
        private class OnClickListenerlmpl implements OnClickListener{
        	public void onClick(View view){
        		switch(view.getId()){
        		case R.id.but:
        			Looper looper = Looper.myLooper();
        			MyHandler myHandler = new MyHandler(looper);
        			myHandler.removeMessages(0);
        			String data = "hahahaha";
        			Message msg = myHandler.obtainMessage(SET,1,1,data);
        			myHandler.sendMessage(msg);
        			break;
        		}
        	}
        }
        private class MyHandler extends Handler{
        	public MyHandler(Looper looper){
        		super(looper);
        	}
        	public void handleMessage(Message msg){
        		switch(msg.what){
        		case 1:
        			MainActivity.this.info.setText(msg.obj.toString());
        		}
        	}
        }
    }
    

      运行效果:

    态度决定高度,细节决定成败,
  • 相关阅读:
    SVN的安装与配置
    nginx之location配置详解及案例
    查看三种MySQL字符集的方法(转)
    JAVA_OPTS设置
    vi/vim 添加或删除多行注释
    Linux 下查看字体
    linux 安装中文字体
    Linux 压缩某个文件夹命令
    Navicat Premium 12.1.16.0安装与激活
    Rsync + sersync 实时同步备份
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/3996216.html
Copyright © 2020-2023  润新知