android動畫之經過子線程來實現動畫java
使用android動畫機制,每每是相對於原始位置來進行參照。android
這裏經過子線程修改物體位置實現動畫。ide
佈局文件:佈局
<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