我需要使用存储在String数组sendArray中的十六进制颜色代码值来更改空白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();
}
}
}
}
最佳答案
您可以首先在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();
}
}
}