W e S D
0 1

android小Demo--七彩霓虹灯效果

  七彩霓虹灯效果,基于网上的小Demo进行修改。

  在android项目values文件夹下创建文件colors.xml,配置七种颜色:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="blue">#0000ff</color>
    <color name="red">#ff0000</color>
    <color name="yellow">#ffff00</color>
    <color name="green">#8cd400</color>
    <color name="pink">#A020F0</color>
    <color name="orange">#ffa500</color>
    <color name="indigo">#4b0082</color>
</resources>

  MainActivity中代码:

	// 当前颜色
	private int currentCount = 0;
	// 颜色ID数组
	private int[] colorList = new int[] { R.color.red, R.color.orange,
			R.color.yellow, R.color.green, R.color.blue, R.color.indigo,
			R.color.pink };
	//textview数组
	private TextView[] viewList = new TextView[colorList.length];

  Handler类 (消息处理器) 帮助主线程进行UI更新

Handler mHandler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
    super.handleMessage(msg);
    if (msg.what == 1) {
      //更新textview颜色
      for (int i = 0; i < viewList.length; i++) {
        viewList[i].setBackgroundResource(colorList[(i + currentCount)% viewList.length]);
      }
      currentCount++;
    }
  }
};

  onCreate()方法中:

//实例化textview
for (int i = 0; i < colorList.length; i++) {
  viewList[i] = new TextView(this);
  //设置控件大小位置
  RelativeLayout.LayoutParams viewparams = new RelativeLayout.LayoutParams(700 - 100 * i, 700 - 100 * i);
  viewparams.addRule(RelativeLayout.CENTER_IN_PARENT);
  viewList[i].setLayoutParams(viewparams);
  //设置起始颜色
  viewList[i].setBackgroundResource(colorList[i]);
  layout.addView(viewList[i]);
}

 计时器的使用:

    //计时器 每200毫秒发送一次消息给主线程更新ui
    new Timer().schedule(new TimerTask() {
      @Override
    public void run() {
      mHandler.sendEmptyMessage(1);
    }
  , 0, 200);        

  运行demo即可展现七彩霓虹灯。

 

posted @ 2016-03-20 15:24  SD.Team  阅读(832)  评论(0编辑  收藏  举报