使用FrameLayout(帧布局) 和Timer实现动态图片

来源:互联网 发布:微分销系统开发源码 编辑:程序博客网 时间:2024/05/29 13:45

 1.实现图片的轮换显示,定义帧布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0,1,2,3"><TableRow><TextView android:text="水果"></TextView><TextView android:text="西瓜 "></TextView><TextView android:text="香蕉"></TextView><TextView android:text="芒果"></TextView></TableRow><TableRow><TextView android:text="language"></TextView><TextView android:text="中文 "></TextView><TextView android:text="英文"></TextView><TextView android:text="日语"></TextView></TableRow><TableRow><TextView android:text="编程语言"></TextView><TextView android:text="C "></TextView><TextView android:text="C++"></TextView><TextView android:text="Java"></TextView></TableRow></TableLayout>
<!--上面的表格布局可以忽略 --><FrameLayout android:id="@+id/frame" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/></LinearLayout>

 2.java 代码:

public class MainActivity extends Activity {private FrameLayout frameLayout=null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //获取布局对象        frameLayout=(FrameLayout) findViewById(R.id.frame);        //使用计时器        Timer timer=new Timer();        timer.scheduleAtFixedRate(new TimerTask() {int i=0;@Overridepublic void run() {i++;System.out.println(i);Message msg=new Message();msg.what=i;i%=3;//发送消息handler.sendMessage(msg);}}, 1000, 1000);    }    //使用Handler实现UI线程与Timer线程之间的通信    Handler handler=new Handler(){    //处理消息更新UI线程@Overridepublic void handleMessage(Message msg) {switch(msg.what){case 1:frameLayout.setForeground(getResources().getDrawable(R.drawable.f));;break;case 2:frameLayout.setForeground(getResources().getDrawable(R.drawable.s));break;case 3:frameLayout.setForeground(getResources().getDrawable(R.drawable.t));break;default:System.out.println("哈哈,没有图片");break;}}        };}


3.在drawable中放了3张图片 f.png,s.png,t.png

原创粉丝点击