ProgressBar updating using Message Handler

You're going to learn how to make a progressbar, which gives you a feedback what's going on in the background.

 

Let say you have a LoadingScreen activity (loadingscreen.xml layout), and a Main activity (main.xml).

 

You'd like to do some job in the Main activity, and update the progressbar status at the same time. To do this, we are going to use Messages. Although, you can update you're progressbar by sending the progressbar instance itself to your Main activity, but that's obviously not the prettiest solution.

What we going to do is:

 

1. Declaring a progressbar instance in LoadingScreen Activity:

So in your LoadingScreen.java, after Oncreate(), you should add something like this line to your codeline: (don't forget to add a progressbar to your layout first!)

 

ProgressBar pb = (ProgressBar)findViewById(R.id.ProgressBar01);

 2. Setting up a Handler to handle Messages from outside: These few line go right after declaring the progressbar. We are also declaring "progress" variable, and update it's value from the Message we get.

Now that we know the progress status, simply just update the progressbar with it. (It has to be an int number, value: 0-100.)

/* Setting up handler for ProgressBar */
pbHandle = new Handler(){
	@Override
  public void handleMessage(Message msg) {
  	/* get the value from the Message */
    int progress = msg.arg1;
    pb.setProgress(progress);
  }
};

 Okay, we finished message handling, now let's send some messages from another (in this case Main) activity.

3. Creating and Sending Messages

Please notice that in the 3rd line, we put the progress value (it depends on your project) into the Message's arg1 variable.

Go to your Main(or any other) activity, and paste the following where you need to send the message about the progress.

/* Creating a message */
Message progressMsg = new Message();
progressMsg.arg1 = progress();
/* Sending the message */
pbHandle.sendMessage(progressMsg);

 That's it.

One more thing: you should not use the same message twice, in the same cycle. If you want to send 2 messages in a cycle, you should create a new message with another instance name, Otherwise your app will be crashed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值