Changing Color of a textView in an infinite loop

时间:2017-06-09 12:43:32

标签: android

I am kind of new in android programming so excuse me for asking this question but I needed help. I want to change color of a textView in an infinite loop I tried this code:

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

    TextView textView = (TextView) findViewById(R.id.textView);

    while(true){
        textView.setTextColor(Color.BLUE);
        try{
            Thread.sleep(500);
        }
        catch (InterruptedException e) {
            Log.e("InterruptedException", "Thread interrupted", e);
        }
        textView.setTextColor(Color.RED);
    }
}

But the problem is that UI doesn't update itself. I even tried to put my code in onStart() but that didn't help either, may somebody please help me where should I put my code so that UI updates itself in an infinite loop?

2 个答案:

答案 0 :(得分:3)

不要担心自己是初学者也不错。

我建议你永远不要使用while()来操作任何视图,直到你阅读Processes and Threads,你必须明白什么是UI线程。

为了解决您的问题: 使用Animations,点击here获取有关该主题的精彩教程 - 它不仅可以帮助您更改视图的颜色,还可以帮助您完成其他任何您想要的操作。

稍后您的知识追求: 您将了解到,您可以通过扩展 View.class 覆盖onDraw()方法来创建自己的自定义视图,然后您想要绘制/颜色/操作的所有内容都是您可以点击here获取更多信息。

玩得开心:)

答案 1 :(得分:2)

It looks like your current code is blocking the main thread of the application, which will prevent the UI from properly handling user interaction, view updates, etc.

If you want to make a change on a schedule, you might want to look into posting a Runnable on to the view. So, something like this:

TextView textView;
Runnable changeTextColorRunnable = new Runnable() {
    public void run() {
        textView.setTextColor(calculateTextColor());
        textView.postDelayed(changeTextColorRunnable, 500);
    }
};

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

    textView = (TextView) findViewById(R.id.textView);

    textView.post(changeTextColorRunnable);
}