(四)Android布局之帧布局(FrameLayout)

时间:2022-03-12 04:34:36

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="@+id/frame">

</FrameLayout>

Activity.java

package com.example.administrator.myapplication;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;

/**
* Created by Administrator on 2015/1/29.
*/
public class BirdActivity extends Activity {
FrameLayout frame=null;
private boolean flag=true;
class MyHandler extends Handler{
int i=0;
//由该类两个方法间的循环调用,实现界面不断更新
public void HandleMessage(Message msg) {
i++;
//总共三幅图,依次显示
show(i % 3);
//再次调用sleep方法
sleep(10);
}
public void sleep(long delayMillis){
//判断是否继续飞翔
if(flag){
//实质上是调用了一次handleMessage
sendMessageDelayed(obtainMessage(),delayMillis);
}
}
}
//该方法被调用已更新帧布局的前景图片
void show(int j){
//获取三张图片
Drawable a=getResources().getDrawable(R.drawable.a);
Drawable b=getResources().getDrawable(R.drawable.b);
Drawable c=getResources().getDrawable(R.drawable.c);
//不同的情况,设置不同的前景
switch (j){
case 0:
frame.setForeground(a);
break;
case 1:
frame.setForeground(b);
break;
case 3:
frame.setForeground(c);
break;
}
}
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.framelayout);
frame=(FrameLayout)findViewById(R.id.frame);
//创建一个Handle子类对象,要调用其方法
final MyHandler myHandler=new MyHandler();
myHandler.sleep(10);
//为fram设置单击事件,当其被单击时,切换图片
frame.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
flag=!flag;
myHandler.sleep(10);
}
});


}
}