Android:setBackgroundColor不能正常工作

时间:2016-10-12 23:41:26

标签: java android

我想创建一个更改ImageView颜色的循环,但它不起作用.. 在Activity的XML文件中,我在ImageView的background属性中提供了一些jpg。颜色来自String Array。日志显示迭代正常..它将ImageView更改为白色(不可见?)

代码:

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);
        }
    };
}

1 个答案:

答案 0 :(得分:0)

//在全局

上声明它
Timer t = new Timer();

//将此代码写入onCreate()或根据您的需要

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);

//

  

确保您为ImageView提供了一些高度宽度   显示空白