Android學習筆記第二彈之事件處理

事件處理:OnclickListener 各種回調函數 使用Handle類在子線程和父線程之間的通信

通過組件的setOnClickListener()爲組件配置響應的事件。分爲三個順序

1.直接觸發OnClickListener()接口的 OnTouch()函數。

2.觸發組件的回調函數,public boolean onTouchEvent(MotionEvent event){}

3.觸發activity的回調函數,public boolean onTouchEvent(MotionEvent event){}

自己編寫程序驗證事件處理

 

事件處理中,Handle類的使用。Handle類是通過子線程發送消息給主線程,主線程根據消息類型執行不同的事件。因爲android規定子線程是不能夠更改主線程的界面組件。

一般的Handle使用方法:

1.創建子線程,在子線程中控制刷新時間。並在到達時間片之後 Handler.sendMessage(Message)傳輸Message數據。

2.在主線程中新建Handle對象。重寫public void handleMessage()方法,並通過此方法獲得message,識別message.what的類型 改變UI組件特徵。

代碼如下

package com.example.handle;

 

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.TextView;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

 

public class MainActivity extends Activity {

 

private TextView textView;

private Handler myHandler;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textView=(TextView)findViewById(R.id.textView1);

this.myHandler=new Handler(){

public void handleMessage(Message msg){

super.handleMessage(msg);

if(msg.what==0x12){

textView.setText("隨機數是"+Math.random());

}

}

};

new Thread(new Runnable(){

public void run(){

try {

while(true){

Message msg=new Message();

msg.what=0x12;

myHandler.sendMessage(msg);

Thread.sleep(1000);

//Log.d("lyb","睡了一秒" );

}

catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

};

}).start();

}

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章