我需要帮助,以1秒钟的间隔在Android中以编程方式更改文本颜色。颜色应该是
答案 0 :(得分:3)
您可以尝试
在科特林
(S) this
或在Java中
val handler = Handler()
val colors = arrayOf(Color.BLUE, Color.WHITE, Color.YELLOW, Color.GREEN)
var i;
val runnable = Runnable {
i = i % colors.size
yourView.setTextColor(colors[i])
i++
handler.postDelayed(this, 1000)
}
handler.postDelayed(runnable, 1000)
答案 1 :(得分:0)
首先在xml文件中创建颜色数组。
<array name="textViewColors">
<item>@color/bright_pink</item>
<item>@color/red</item>
<item>@color/orange</item>
<item>@color/yellow</item>
<item>@color/chartreuse</item>
<item>@color/green</item>
<item>@color/spring_green</item>
<item>@color/cyan</item>
<item>@color/azure</item>
<item>@color/blue</item>
<item>@color/violet</item>
<item>@color/magenta</item>
</array>
并创建一个线程:
TextView textView;
//an array to access the color we declare in xml file
int[] textViewColors = context.getResources().getIntArray(R.array.textViewColors);
Thread changeColor = new Thread() {
@Override
public void run() {
try {
sleep(5000); //time that set interval. this is for 5 sec
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i=0;i<=textViewColors.size();i++){
textView.setTextColor(textViewColors[i]);
}
}
});
} catch (Exception e) {
}
}
};
,并在任意位置执行线程。例如在onCreate中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
---> changeColor.start();
}
我希望它对您有用。