幀布局容器為每個加入其中的元件建立一個空白的區域(稱為一幀),所有每個子元件占據一幀,這些幀都會根據gravity屬性執行自動對齊。
FrameLayout的常用XML屬性和相關方法
XML屬性
相關方法
說 明
android:foreground
setForeground(Drawable)
設定該幀布局容器的前景圖像
android:foregroundGravity
setForegroundGravity(int)
定義繪制前景圖像的gravity屬性
下面的布局界面定義使用FrameLayout布局,并向該布局容器中添加了7個TextView,這7個TextView的高度完全相同,而寬度逐漸減少——這保證最先添加的TextView不會被完全遮擋;而且設定了7個TextView的背景色漸變。
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/View01"
android:layout_width="210dp"
android:layout_height="200dp"
android:background="#ff0000"/>
android:id="@+id/View02"
android:layout_width="180dp"
android:layout_height="200dp"
android:background="#dd0000"/>
android:id="@+id/View03"
android:layout_width="150dp"
android:layout_height="200dp"
android:background="#bb0000"/>
android:id="@+id/View04"
android:layout_width="120dp"
android:layout_height="200dp"
android:background="#990000"/>
android:id="@+id/View05"
android:layout_width="90dp"
android:layout_height="200dp"
android:background="#770000"/>
android:id="@+id/View06"
android:layout_width="60dp"
android:layout_height="200dp"
android:background="#550000"/>
android:id="@+id/View07"
android:layout_width="30dp"
android:layout_height="200dp"
android:background="#330000"/>
效果如圖:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIu9Wa0FGZuVWbt92YlJXPlNmc192cf1Gd1ZyclR3bu91blNXPtVXakVWbf1Gd1ZSZ09mb9QnblRnbvN2XtRXdmUmbpt2clxWYt1jbnlWYw1WYj9Vb0V3PmNGZiBzYzgzN1MDZvwFcvwVbvNmL1h2cuFWaq5yd3d3Lc9CX6MHc0RHaiojIsJye.jpg)
顔色漸變.jpg
霓虹燈效果
如果考慮輪換上面幀布局中的7個TextView的背景色,就會看到上面的顔色漸變條不斷地變化,就像大街上的霓虹燈。
private int currentColor = 0;
//定義一個顔色數組
final int[] colors = new int[]{
R.color.color7,
R.color.color6,
R.color.color5,
R.color.color4,
R.color.color3,
R.color.color2,
R.color.color1
};
final int[] names = new int[]{
R.id.View01,
R.id.View02,
R.id.View03,
R.id.View04,
R.id.View05,
R.id.View06,
R.id.View07,
};
TextView[] views = new TextView[7];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
for (int i = 0; i < 7; i++) {
views[i] = findViewById(names[i]);
}
@SuppressLint("HandlerLeak")
final Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == 0x1122) {
for (int i = 0; i < 7 - currentColor; i++) {
views[i].setBackgroundResource(colors[i + currentColor]);
}
for (int i = 7 - currentColor, j = 0; i < 7; i++, j++) {
views[i].setBackgroundResource(colors[j]);
}
}
super.handleMessage(msg);
}
};
//定義一個線程周期性地改變currentColor變量值
new Timer().schedule(new TimerTask() {
@Override
public void run() {
currentColor++;
if (currentColor >= 6) {
currentColor = 0;
}
Message m = new Message();
m.what = 0x1122;
handler.sendMessage(m);
}
}, 0, 500);
}