Android中Handler的简单应用(二)

来源:互联网 发布:python字典添加元素 编辑:程序博客网 时间:2024/05/29 13:00

对于Handler的简单应用现在上升到了Handler发送Message上

MainActivity.java

package com.whisker.handlertest2;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;public class MainActivity extends Activity {private ProgressBar progressBar;private Button button;private Button stopButton;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        progressBar = (ProgressBar) findViewById(R.id.progressBar);        button = (Button) findViewById(R.id.button);        button.setOnClickListener(clickListener);        stopButton = (Button) findViewById(R.id.stop);        stopButton.setOnClickListener(clickListener);    }        private OnClickListener clickListener = new OnClickListener() {@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.button:handler.post(update);break;case R.id.stop:Log.i("whisker", "stop");handler.removeCallbacks(update);break;}}};Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {//super.handleMessage(msg);progressBar.setProgress(msg.arg1);handler.post(update);}};Runnable update = new Runnable() {int i = 0;@Overridepublic void run() {i += 5;Message message = handler.obtainMessage();message.arg1 = i;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}handler.sendMessage(message);if(i== 100){handler.removeCallbacks(update);}}};}

activity_main.xml

<LinearLayout 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:orientation="vertical" >    <ProgressBar         android:id="@+id/progressBar"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"/>        <Button         android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Start"/>        <Button         android:id="@+id/stop"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stop"/></LinearLayout>

在测试的时候发现卡顿的现象非常明显,有时候Stop的作用会丢失,看来还是需要优化的,虽然现在还不知道怎么做。。。


效果图:


0 0
原创粉丝点击