我需要使用存储在String数组transmitArray中的十六进制颜色代码值来更改空白ImageView的颜色,并在TransmitFreq中指定延迟。但是,当我运行代码时,只显示第一种颜色(对应于第一个数组值)。
我尝试了三种方法,即(thread.sleep),倒数计时器和post.delayed但没有成功。如果有人能指出我做错了什么,我将不胜感激。
public class Main2Activity extends AppCompatActivity {
String [] transmitArray;
long transmitFreq;
public static int i;
public static View colourView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main2);
final String transmitArray [] = getIntent().getStringArrayExtra("COLOUR_DATA");
transmitFreq = getIntent().getLongExtra("FREQ_VALUE", 0);
int arrayLength = transmitArray.length;
colourView = findViewById(R.id.colourBox);
/*
//Method 1: Using Countdown timer
new CountDownTimer(transmitFreq*(transmitArray.length), transmitFreq) {
public void onTick(long millisUntilFinished) {
colourView.setBackgroundColor(Color.parseColor(transmitArray[i]));
i++;
}
public void onFinish() {
i=0;
}
}.start();
//Method 2: Using post.delayed
Handler handler = new Handler();
for (i = 0; i < arrayLength ; i++) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
String transmitColour = transmitArray[i];
colourView.setBackgroundColor(Color.parseColor(transmitColour));
}
}, transmitFreq);
}*/
//Method 3: Using thread.sleep
for (i = 0; i < arrayLength ; i++) {
String transmitColour = transmitArray[i];
colourView.setBackgroundColor(Color.parseColor(transmitColour));
try {
Thread.sleep(transmitFreq);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
答案 0 :(得分:0)
您最初可以在onCreate方法中使用默认颜色,然后尝试OnCreate方法之外的3种方法。试试这段代码
public class Main2Activity extends AppCompatActivity {
String [] transmitArray;
long transmitFreq;
public static int i;
public static View colourView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main2);
colourView = findViewById(R.id.colourBox);
}
final String transmitArray [] = getIntent().getStringArrayExtra("COLOUR_DATA");
transmitFreq = getIntent().getLongExtra("FREQ_VALUE", 0);
int arrayLength = transmitArray.length;
/*
//Method 1: Using Countdown timer
new CountDownTimer(transmitFreq*(transmitArray.length), transmitFreq) {
public void onTick(long millisUntilFinished) {
colourView.setBackgroundColor(Color.parseColor(transmitArray[i]));
i++;
}
public void onFinish() {
i=0;
}
}.start();
//Method 2: Using post.delayed
Handler handler = new Handler();
for (i = 0; i < arrayLength ; i++) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
String transmitColour = transmitArray[i];
colourView.setBackgroundColor(Color.parseColor(transmitColour));
}
}, transmitFreq);
}*/
//Method 3: Using thread.sleep
for (i = 0; i < arrayLength ; i++) {
String transmitColour = transmitArray[i];
colourView.setBackgroundColor(Color.parseColor(transmitColour));
try {
Thread.sleep(transmitFreq);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}