Android帧式布局实现自动切换颜色

本文实例为大家分享了Android帧式布局实现自动切换颜色的具体代码,供大家参考,具体内容如下

效果:

Android帧式布局实现自动切换颜色_第1张图片

实现:

activity_main.xml




    

        

        

        


    

    
        

ActivityMain.java

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private TextView tvBottom;
    private TextView tvMiddle;
    private TextView tvTop;
    private int[] colors;
    private Handler handler;
    private Thread thread;
    private boolean isRunning;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //利用布局资源设置用户界面
        setContentView(R.layout.activity_main);
        //通过资源标识符获取控件实例
        tvBottom = findViewById(R.id.tvBottom);
        tvMiddle = findViewById(R.id.tvMiddle);
        tvTop = findViewById(R.id.tvTop);
        //初始化颜色数组
        colors = new int[]{Color.RED, Color.BLUE, Color.GREEN};

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0x0001) {
                    //切换颜色
                    int temp = colors[0];
                    for (int i = 0; i < colors.length - 1; i++) {
                        colors[i] = colors[i + 1];
                    }
                    colors[colors.length - 1] = temp;
                    // 根据切换后的颜色数组来设置三层标签的背景色
                    tvBottom.setBackgroundColor(colors[0]);
                    tvMiddle.setBackgroundColor(colors[1]);
                    tvTop.setBackgroundColor(colors[2]);
                }
            }
        };

    }

    /**
     * 【开始】按钮单击事件处理方法
     */
    public void doStart(View view) {
        // 设置线程运行控制变量
        isRunning = true;
        // 创建子线程,定时发送消息
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    // 向主线程发送消息
                    handler.sendEmptyMessage(0x0001);
                    // 让线程睡眠500毫秒
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        // 启动线程
        thread.start();
    }

    /**
     * 【停止】按钮单击事件处理方法
     */
    public void doStop(View view) {
        // 设置线程运行控制变量
        isRunning = false;
        // 销毁子线程
        thread = null;
    }
}

string.xml


    帧式布局:颜色切换
    底层
    中层
    顶层
    开始
    结束

原本想用Timer定时器实现,但是不知怎么的总是报错,所有就使用了这个旧方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Android帧式布局实现自动切换颜色)