2017-08-30 27 views
1

我想使用TransitionDrawable類製作動畫,但需要單獨的文件transition.xml。在那裏我定義了我改變的圖像。如何從Java代碼爲ImageView製作圖像變化動畫

我需要在Java代碼中定義它們,因爲我不知道我將更改哪些圖像。我有很多圖像,我不小心只會得到兩個圖像,這兩個圖像會相互變化。我能做什麼?也許我需要另一堂課。

代碼transition.xml:

public class TransitionActivity extends Activity 
     implements OnClickListener { 

    private ImageView image; 
    private TransitionDrawable mTransition; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     image = (ImageView)findViewById(R.id.image); 
     image.setOnClickListener(this); 

     Resources res = this.getResources();  
     mTransition = (TransitionDrawable)res.getDrawable(R.drawable.transition); 
    } 

    @Override 
    public void onClick(View v) { 
     image.setImageDrawable(mTransition);  
     mTransition.startTransition(1000); 
    } 
} 

回答

1

您可以使用類的constructor編程方式創建一個TransitionDrawable。您不需要從XML獲取它。這爲您提供了動態分配它之間轉換的Drawable的靈活性。

// drawable1 and drawable2 can be dynamically assigned in your Java code 

Drawables[] drawables = new Drawables[] { 
    drawable1, drawable2 
}; 
mTransition = new TransitionDrawable(drawables);