2014-02-10 17 views
1

我正在參加Coursera課程的Android編程。這裏是什麼,我試圖做一個說明...Android - 我怎樣才能讓一個圖像的動畫在一定的時間間隔發生?

Slide and fade interval

下面的代碼我到目前爲止...

XML:

<Button 
     android:id="@+id/startbutton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/leftfoot" 
     android:layout_alignRight="@+id/leftfoot" 
     android:onClick="startRhythmandAnimation" 
     android:text="@string/start_button" /> 

的Java:

public class Assignment3MainActivity extends Activity { 

private View mMileTimeGoal; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_assignment3_main); 
    mMileTimeGoal = findViewById(R.id.miletimegoal); 
} 

public void startRhythmandAnimation() { 
    String MileTime = mMileTimeGoal.getContext().toString(); 
    String[] time_array = MileTime.split(":"); 
    int hours = Integer.parseInt(time_array[0]); 
    int minutes = Integer.parseInt(time_array[1]); 
    int seconds = Integer.parseInt(time_array[2]); 
    int duration = 3600 * hours + 60 * minutes + seconds; 
    int steps_per_second = 3; 

    int running_rate = duration * steps_per_second; 

    View rightfoot = findViewById(R.id.rightfoot); 
    View leftfoot = findViewById(R.id.leftfoot); 

    rightfoot.setVisibility(View.VISIBLE); 
    Animation anim = AnimationUtils.makeInChildBottomAnimation(this); 
    rightfoot.startAnimation(anim); 

    leftfoot.setVisibility(View.VISIBLE); 
    leftfoot.startAnimation(anim); 
} 

任何想法如何形成我的算法,可以滑動和淡出我的右腳視圖和左腳視圖?

我應該使用while循環並啓動某種類型的定時器嗎?

回答

2

活動

private Handler mHandler;  
private long mInterval = 1000; 
private View mLeftfoot; 
private Animation mFootAnim; 

public void onCreate(Bundle bundle) { 
    ... 
    mHandler = new Handler(); //.os package class when importing 
    mLeftfoot = findViewById(R.id.leftfoot); 
    mFootAnim = AnimationUtils.loadAnimation(this, R.anim.foot); 
    stepRecursive(); 
} 

private void stepRecursive() { 
    mHandler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      mLeftFoot.startAnimation(mFootAnim); 
      stepRecursive(); 
     } 
    }, mInterval); 
} 

/res/anim/foot.xml

<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <translate android:fromYDelta="0" android:toYDelta="-15" android:duration="400"/> 
    <alpha android:fromAlpha="1.0" android:toAlpha="0" android:duration="400" /> 
</set> 

那直客我的頭頂(因此未經測試),但應該有很多讓你在正確的去方向

+0

非常感謝!幾個問題雖然...我可以只將foot.xml內容放在我的/layout/main.xml中?另外,這個區間是否固定?我是否更改mInterval以根據用戶的英里時間目標進行調整? – StacyM

+0

是調整您的時間目標的時間間隔。不,你不能合併XML,res目錄中有不同文件夾的原因是它們服務於不同目的 –

+0

如果你有時間,請參閱我最新的Logcat異常:http://stackoverflow.com/questions/21671129/ android-illegalstateexception-could-not-execute-method-of-the-activity-cause – StacyM

相關問題