This exercise extends from the previous article, AndroidRunnable, with Runnable Thread.
Save the four graphics, used to form the animation of a rotating arrow, in the /res/drawable/ folder.
Add a ImageView in main.xml to display the animation.
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/i"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/myImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
/>
</LinearLayout>
Modify update_i() to change i, and load ViewImage with arrow_01, arrow_02, arrow_03 and arrow_04 one by one.
package com.exercise.AndroidRunnable;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
public class AndroidRunnable extends Activity{
int i = 0;
TextView myi;
ImageView MyImageView;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
update_i();
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myi =(TextView)findViewById(R.id.i);
MyImageView = (ImageView)findViewById(R.id.myImageView);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Thread myThread=new Thread(new Runnable() {
public void run() {
while(true){
try {
handler.sendMessage(handler.obtainMessage());
Thread.sleep(1000);
}
catch (Throwable t) {
}
}
}
});
myThread.start();
}
private void update_i()
{
switch(i){
case 0:
i++;
MyImageView.setImageResource(R.drawable.arrow_01);
break;
case 1:
i++;
MyImageView.setImageResource(R.drawable.arrow_02);
break;
case 2:
i++;
MyImageView.setImageResource(R.drawable.arrow_03);
break;
case 3:
i = 0;
MyImageView.setImageResource(R.drawable.arrow_04);
break;
}
myi.setText(String.valueOf(i));
}
}
AndroidRunnable.java can be downloaded here.For sure, it's not a good practice to implement animation. It is used to show the implementation of Runnable Thread, and Handle.
Here is another article about Animation background, using animation-list and AnimationDrawable.
No comments:
Post a Comment