用李刚书中的教程做出了一个关于帧布局的弥红灯效果:
我把相关代码贴出来,xml档:
<FrameLayout xmlns:android ="http://schemas.android.com/apk/res/android"
android:id= "@+id/ll"
android:layout_width= "match_parent"
android:layout_height= "match_parent" >
<TextView
android:id ="@+id/v1"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="320dp"
android:height ="320dp" />
<TextView
android:id ="@+id/v2"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="280dp"
android:height ="280dp" />
<TextView
android:id ="@+id/v3"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="240dp"
android:height ="240dp" />
<TextView
android:id ="@+id/v4"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="200dp"
android:height ="200dp" />
<TextView
android:id ="@+id/v5"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="160dp"
android:height ="160dp" />
<TextView
android:id ="@+id/v6"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:width ="120dp"
android:height ="120dp" />
</ FrameLayout>
,。这个就很简单了。、 。。 主要是这里看一下相关代码:
package com.dsun.first;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private int curnum = 0;//颜色迭代计数器
//定义所有的颜色
final int [] colors = new int[]{
R.color. color1 ,
R.color. color2 ,
R.color. color3 ,
R.color. color4 ,
R.color. color5 ,
R.color. color6
};
//定义所有TextView的id
final int [] names = new int[]{
R.id. v1 ,
R.id. v2 ,
R.id. v3 ,
R.id. v4 ,
R.id. v5 ,
R.id. v6
};
//所有的TextView
TextView[] tvs = new TextView[names .length ];
//异步处理类
final Handler h = new Handler(){
public void handleMessage(Message msg) {
//如果调用信息为0x123的话 继续访问
if (msg.what == 0x123){
for (int i = 0 ; i < tvs .length ; i ++){
tvs[i].setBackgroundColor( colors[(i + curnum ) % names .length ]);
}
curnum ++ ;
}
super .handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
for( int i = 0 ; i < names. length ; i ++){
tvs[i] = (TextView)findViewById(names [i]);
}
new Timer().schedule( new TimerTask() {
@Override
public void run() {
h.sendEmptyMessage(0x123);
}
}, 0, 200);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main , menu);
return true ;
}
}
这里边代码还是有点意思的。 其中R.colors.xxxx是在colors.xml中:
这个是需要我们来建的, 在values中。
其次里边用到了一个Timer的小调度,这是在java基础中已经学过的。
但是又意思是为什么组件切换颜色时,不直接在Timer中的内部类的run中进行切换呢。 看下李刚的这段话:
这样我们就了解了,view组件是线程不安全的。好吧,大概主要的就是这些.