android动画之通过子线程来实现动画
使用android动画机制,往往是相对于原始位置来进行参照。
这里通过子线程修改物体位置实现动画。
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/show" android:layout_marginLeft="20dp" android:layout_marginTop="40dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button1" android:onClick="MyCLick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="行动" /> <Button android:id="@+id/button2" android:onClick="MyCLick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginRight="28dp" android:layout_toLeftOf="@+id/button1" android:text="获取位置" /> </RelativeLayout>
动画代码:
public class MainActivity extends Activity {
TextView textView;
MyRuns myRuns;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.show);
myRuns=new MyRuns(new MyHead(textView, 4, 8), true);//位移动画
}
static class MyHead extends Handler {// 坐标动画
View view;// 操作元素
float cx;
float cy;
public MyHead(View view, float cx, float cy) {
super();
this.view = view;
this.cx = cx;
this.cy = cy;
}
@Override
public void handleMessage(Message msg) {
// 更新ui
view.setX(view.getX() + cx);
view.setY(view.getY() + cy);
super.handleMessage(msg);
}
}
// 子线程更新位置
class MyRuns implements Runnable {//更新UI界面
MyHead head;
boolean isFire = false;
public MyRuns(MyHead head, boolean isFire) {
super();
this.head = head;
this.isFire = isFire;
}
public boolean isFire() {
return isFire;
}
public void setFire(boolean isFire) {
this.isFire = isFire;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if (!isFire) {
break;//停止动画
}
Thread.sleep(80);
Message message = new Message();
message.what = 3;
message.obj = "";
head.sendMessage(message);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
//开始运动
void StartThreed(MyRuns myRuns){
myRuns.setFire(true);//开启
new Thread(myRuns).start();
}
public void MyCLick(View view) {
if (view.getId() == R.id.button1) {
StartThreed(myRuns);
} else if (view.getId() == R.id.button2) {
myRuns.setFire(false);//结束子线程
Toast.makeText(getApplicationContext(),
"坐标" + textView.getX() + "||" + textView.getY(),
Toast.LENGTH_SHORT).show();
}
}
}
原文地址:http://sijienet.com/bbs/?leibie=showinfo&id=57