使用handler技术

1.使用handler技术动态修改进度条的进度

  • 超级简单的一个小东西。输入一个数字x(0<x<=100),让进度条每秒走x长度,就是步长。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProgressBarActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="50dp">

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请输入步长:"></TextView>

    <EditText
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:id="@+id/edText_1"></EditText>

    </LinearLayout>


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_start"
        android:text="开始"
        android:layout_marginTop="50dp"></Button>

    <ProgressBar
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:paddingTop="50dp"
        android:progress="0"
        android:id="@+id/pgBar1"/>

</LinearLayout>
package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class ProgressBarActivity extends AppCompatActivity {

    ProgressBar pgBar1;
    Button btn_start;
    EditText edText_1;


        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_progress_bar);
            pgBar1 = findViewById(R.id.pgBar1);


            btn_start=findViewById(R.id.btn_start);
            btn_start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("start...");
                    new MyThread().start();
                    System.out.println("end");
                }
            });
        }

    class MyThread extends Thread {
        public void run() {
            edText_1=findViewById(R.id.edText_1);
            int step=Integer.parseInt(edText_1.getText().toString());
            int progress =step;

            for (int i = 0; i < 1+100/step; i++) {
                Message msg = new Message();//每次发送,必须是单独的消息,不能定义一个消息,多次发送
                msg.arg1 = progress;
                msg.what = 1;
                System.out.println("progress=" + progress);
                handler.sendMessage(msg);
                progress += step;

                if (progress>100)
                    progress=100;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1)
                pgBar1.setProgress(msg.arg1);
        }
    };
    }



在java代码中出现了step和progress两个东西,在写代码的时候,就有点懵逼。step是输入的数,每一秒钟往前走的长度。而progress是当前进度条的长度
2.图片和质数。输入一个值,点击按钮,调用子线程计算质数。点击换图片。准备了三张图片,定时更换。循环次数为PicThread里的run方法的for循环里面的i的上界。因为三张图片,设置的i<14,14/3=4…2(除法,余数),所以会停留在第二张图片上。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HandlerMainThreadActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="上界:"/>

        <EditText
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/edit_upper"></EditText>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="计算质数"
            android:layout_marginLeft="20dp"
            android:id="@+id/math_prime"
            android:onClick="btnCalculateClick"></Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示图片"
            android:layout_marginLeft="20dp"
            android:id="@+id/btn_pic"
            android:onClick="btnShowClick"></Button>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="质数有:"></TextView>

        <TextView
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:id="@+id/textV_result"></TextView>
    </LinearLayout>

    <ImageView
        android:id="@+id/show_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#673AB7"></ImageView>
</LinearLayout>
package com.example.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class HandlerMainThreadActivity extends AppCompatActivity {

    EditText edit_upper;
    TextView textV_result;
    Handler mainHandler;
    ImageView show_pic;
    int[] images={R.mipmap.fan,R.mipmap.bee,R.mipmap.run};
    int index=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_main_thread);

        edit_upper=findViewById(R.id.edit_upper);
        textV_result=findViewById(R.id.textV_result);
        show_pic=findViewById(R.id.show_pic);

    }
    Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {//Bundle
            if(msg.what==123){
                List<Integer> list=msg.getData().getIntegerArrayList("nums");
                textV_result.setText(list.toString());
            }
            if(msg.what==456){
                show_pic.setImageResource(images[(index++)%3]);
            }
        }
    };
    //计算素数按钮方法
    public void btnCalculateClick(View v){
        new CalThread().start();
    }
    //显示图片按钮方法

    public void btnShowClick(View v){

        new PicThread().start();
    }
    class CalThread extends Thread{
        public void run(){
            int upper=Integer.parseInt(edit_upper.getText().toString().trim());
            ArrayList<Integer> nums = new ArrayList<Integer>();
            // 计算从2开始、到upper的所有质数,斐波那契数列,别的计算的方法
            outer:
            for (int i = 2 ; i <= upper ; i++) {
                // 用i除以从2开始、到i的平方根的所有数
                for (int j = 2 ; j <= Math.sqrt(i) ; j++) {
                    // 如果可以整除,表明这个数不是质数
                    if(i != 2 && i % j == 0){
                        continue outer;
                    }
                }
                nums.add(i);
            }
            Bundle bundle=new Bundle();
            bundle.putIntegerArrayList("nums",nums);
            Message message=new Message();
            message.setData(bundle);
            message.what=123;
            handler.sendMessage(message);
            //txtResult.setText(nums.toString());//能显示结果,但是接着就报错了,因为子线程不允许修改主界面的控件的值
        }
    }
    class PicThread extends Thread{
        public void run(){
            for(int i=0;i<14;i++){
                //给handler发送10次消息\

                handler.sendEmptyMessage(456);
                try{Thread.sleep(1000);}
                catch(InterruptedException e){}
            }
        }
    }

}

原创文章 9 获赞 1 访问量 99

猜你喜欢

转载自blog.csdn.net/weixin_41225974/article/details/106002244