Android编程开发之seekBar采用handler消息处理操作的方法

时间:2021-10-10 02:58:10

本文实例讲述了android编程开发之seekbar采用handler消息处理操作的方法。分享给大家供大家参考,具体如下:

该案例简单实现进度条可走,可拖拽的功能,下面请看源码:

布局文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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=".mainactivity" >
 <seekbar
  android:id="@+id/seekbar1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_alignparentleft="true"
  android:layout_alignparenttop="true" />
</relativelayout>

java文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.example.lession16_seekbar;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.app.activity;
import android.view.menu;
import android.widget.seekbar;
public class mainactivity extends activity {
 private seekbar seekbar;
 private static final int max_progress =100;
 private int current_progress=10;
 private static final int pro=1;
 private handler handler;
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  seekbar = (seekbar) this.findviewbyid(r.id.seekbar1);
  seekbar.setmax(max_progress);
 /* new thread(new runnable() {
   @override
   public void run() {
    while(true){
     try {
      thread.sleep(600);
      current_progress+=10;
      seekbar.setprogress(current_progress);
     } catch (interruptedexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
     }
    }
   }
  }).start();*/
  handler = new handler(){
    @override
   public void handlemessage(message msg) {
    super.handlemessage(msg);
    switch (msg.what) {
    case pro:
      if(current_progress>=max_progress){
      }else{
       current_progress+=1;
       seekbar.incrementprogressby(1);
       handler.sendemptymessagedelayed(pro, 600);
      }
     break;
    default:
     break;
    }
   }
  };
  current_progress=current_progress>0?current_progress:0;
  seekbar.setprogress(current_progress);
  handler.sendemptymessage(pro);
 }
 @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;
 }
}

效果图(自动走):

Android编程开发之seekBar采用handler消息处理操作的方法

希望本文所述对大家android程序设计有所帮助。