Android中實現多彩的霓虹燈

來源:互聯網
上載者:User

標籤:ack   etc   his   neon   size   context   public   文本   一閃一閃   

1、布局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainll"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lixc.neonlight.MainActivity"
android:orientation="vertical">

</LinearLayout>

2、color.xml檔案

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="color1">#ffff0000</color>
<color name="color2">#ffff6600</color>
<color name="color3">#ffffff00</color>
<color name="color4">#ff00ff00</color>
<color name="color5">#ff00ffff</color>
<color name="color6">#ff0000ff</color>
<color name="color7">#ff6600ff</color>
</resources>

3、在MainActivity中聲明成員變數

private Handler handler;
private static LinearLayout linearLayout;
public static TextView[] textViews = new TextView[14];
int[] bgColor = new int[]{R.color.color1, R.color.color2, R.color.color3,
R.color.color4, R.color.color5, R.color.color6, R.color.color7};
private int index = 0;

4、在MainActivity中的onCreate()方法中,添加文字框組件到線性布局管理器中

linearLayout = (LinearLayout)findViewById(R.id.mainll);
int height = this.getResources().getDisplayMetrics().heightPixels;
for (int i=0;i<textViews.length;i++){
textViews[i] = new TextView(this);
textViews[i].setWidth(this.getResources().getDisplayMetrics().widthPixels);
textViews[i].setHeight(height/textViews.length);
linearLayout.addView(textViews[i]);
}

5、建立新線程,重寫run()方法

new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
try {
Thread.sleep(new Random().nextInt(1000));
}catch (Exception e){
e.printStackTrace();
}
}
}
}).start();

6、建立一個Handler對象,重寫handleMessage()方法

handler = new Handler(){
@Override
public void handleMessage(Message msg){
int temp = 0;
switch (msg.what){
case 1:
for (int i=0;i<textViews.length;i++){
temp = new Random().nextInt(bgColor.length);
if (index == temp){
temp++;
if (temp == bgColor.length){
temp = 0;
}
}
index = temp;
textViews[i].setBackgroundColor(getResources().getColor(bgColor[index]));
}
break;
default:
break;
}
super.handleMessage(msg);
}
};

7、實現效果

這裡只是一張圖片,實際上是一閃一閃的效果。

Android中實現多彩的霓虹燈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.