android - 在两种布局颜色之间反复翻转

标签 android android-layout

我正在开发一个应用程序,在该应用程序中,我试图在两种颜色的布局(线性布局)之间不断切换,但颜色没有按预期变化。当我运行该应用程序时,它会等待,只有最后提到的颜色被更改,而且也只有一次,我怀疑一旦应用程序试图更改其颜色,布局就无法更改颜色,结果该应用程序只能更改一次颜色。

下面是代码

闪光器.java

package com.tutorial.flasher;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
//import android.os.SystemClock;
import android.widget.LinearLayout;


public class flasher extends Activity {
    /** Called when the activity is first created. */
     LinearLayout llaLayout;
     int a,b = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        llaLayout = (LinearLayout)findViewById(R.id.layo);

        for (int i=0;i<4;i++)
        {
            //SystemClock.sleep(2000);

            //llaLayout.buildDrawingCache()
            Thread.currentThread();
            try
            {
            Thread.sleep(2000);
            }
            catch (Exception e)
            {
                e.notifyAll();

            }
            llaLayout.setBackgroundColor(Color.parseColor("#0000FF"));

            //SystemClock.sleep(2000);
            Thread.currentThread();
            try
            {
            Thread.sleep(2000);
            }
            catch (Exception e)
            {
                e.notifyAll();

            }
            llaLayout.setBackgroundColor(Color.parseColor("#FF0000"));

        //  SystemClock.sleep(2000);
        }
    }
}

我在布局中只得到红色。

谢谢, 席德

最佳答案

您可以使用 Handler 实现此目的。 例如:

private boolean bool = true;
llaLayout = (LinearLayout)findViewById(R.id.layo);
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable(){
            @Override
            public void run() {
                mHandler.postDelayed(this, 1000);
                changeColor();              
            }
            private void changeColor() {
                if (bool) {
                    llaLayout.setBackgroundColor(Color.RED);
                    bool = false;
                } else {
                   llaLayout.setBackgroundColor(Color.BLUE);
                    bool  = true;
                }               
            }}, 1000);

此代码将递归调用相同的函数 changeColor(),其中 1000 是下次调用它的时间(以毫秒为单位)。 希望对您有所帮助。

关于android - 在两种布局颜色之间反复翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5124314/

相关文章:

android - Match_parent 布局内部高度与 wrap_content 高度

android - 此应用程序不能树摇图标字体。 Android 部署的 Flutter 构建错误

java - 表 Entry_table 没有名为 DATE 的列(代码 1)

java - 在 Android 中从 JSON 文件生成菜单项

android - 自定义全局应用程序类中断与 "android.app.Application cannot be cast to"

android - 找不到类 'android.graphics.drawable.RippleDrawable

android - mdpi、hdpi、xhdpi 和 xxhdpi 的图像分辨率

android - 在选择 EditText 之前禁用 Android 中的软件键盘

Android Studio 重命名附加了库模块的模块包

android - 在应用程序启动时关闭抽屉导航