是否可以立即更新视图的属性?

时间:2019-03-28 15:41:22

标签: java android

我是Android Studio的初学者,我几乎在所有地方都进行过搜索,但没有找到适合我的东西。

我想在每次无限循环更改背景颜色后立即更新视图。我尝试使用invalidate(),但是在点击后,视图仍然是白色的。更改后如何重新绘制视图?

public class Main extends AppCompatActivity {
    static int r = 0, g = 0, b = 0;
    static int current, direction;

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

        final View view = findViewById(R.id.textView);
        final View root = view.getRootView();

        view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                while(true) {
                    rainBow();
                    root.setBackgroundColor(Color.rgb(r, g, b));
                    view.invalidate();
                    root.invalidate();
                }
            }
        });
    }

    public static void rainBow() {
        if(r == 0 && g == 0 && b == 0) {
            current = 1;
            direction = 1;
        } else if(r == 255 && g == 0 && b == 0) {
            current = 2;
            direction = 1;
        } else if(r == 255 && g == 255 && b == 0) {
            current = 1;
            direction = -1;
        } else if(r == 0 && g == 255 && b == 0) {
            current = 3;
            direction = 1;
        } else if(r == 0 && g == 255 && b == 255) {
            current = 2;
            direction = -1;
        } else if(r == 0 && g == 0 && b == 255) {
            current = 1;
            direction = 1;
        } else if(r == 255 && g == 0 && b == 255) {
            current = 3;
            direction = -1;
        }

        switch(current) {
            case 1:
                r += direction;
                break;

            case 2:
                g += direction;
                break;

            case 3:
                b += direction;
                break;
        }
    }
}

0 个答案:

没有答案