简体   繁体   English

Android:setBackgroundColor无法正常工作

[英]Android : setBackgroundColor not working

I want to make a loop which changes the color of the ImageView but it isn't working.. In the XML file of the Activity I gave some jpg in the background attribute of ImageView . 我想做一个循环,以更改ImageView的颜色,但是不起作用。在Activity的XML文件中,我在ImageView的background属性中提供了一些jpg。 The colors are from the String Array. 颜色来自字符串数组。 Log shows iteration is ok.. It changes ImageView to white (not visible? ) 日志显示迭代可以。.它将ImageView更改为白色(不可见?)

Code: 码:

public class MainActivity extends AppCompatActivity {

    ImageView imV;
    int totalStep = 4;
    int step = 0;
    private Handler handler;
    String colors[] = {"#000000", "#ff4455", "#ff1133", "#ff0000", "#00ffff"};

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

        imV = (ImageView) findViewById(R.id.imageView);

        handler = new Handler();
        handler.postDelayed(runnable, 1000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (step == totalStep) {
                step = 0;
            } else {
                step++;
            }
            imV.setBackgroundColor(Color.parseColor(colors[step]));
            Log.d("Tick", " " + step);
            Log.d("color", " _ " + colors[step]);

            handler.postDelayed(this, 1000);
        }
    };
}

// declare it on global //在全局上声明

Timer t = new Timer();

// write this code in onCreate() or as per your need //将此代码写入onCreate()或根据您的需要

imV = (ImageView) findViewById(R.id.imageView); imV =(ImageView)findViewById(R.id.imageView);

    t.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (step == totalStep) {
                            step = 0;
                        } else {
                            step++;
                        }
                        imV.setBackgroundColor(Color.parseColor(colors[step]));
                        Log.e("Tick", " " + step);
                        Log.e("color", " _ " + colors[step]);
                    }
                });
        }
    }, 0, 1000);

// //

make sure you have given some height width to your ImageView else its shows blank 确保您已为ImageView设置了一些高度宽度,否则其显示为空白

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM