2015-11-25 62 views
2

我想旋轉按鈕內的圖像,單擊按鈕。我只用ImageView嘗試,它的工作原理,但爲了便於使用,我需要使用Button而不是ImageView。Android - 旋轉按鈕內的圖像

點擊之前:enter image description here

這裏的向下箭頭按鈕是背景。

點擊後:enter image description here

點擊按鈕顯示額外的數據和背景箭頭旋轉。點擊時如何動畫和旋轉按鈕背景?參考

佈局代碼:

<RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_vertical" > 

      <LinearLayout 
       android:id="@+id/cases_actions_row" 
       android:layout_height="wrap_content" 
       android:layout_width="match_parent" 
       android:orientation="horizontal" > 

       <Button 
        android:id="@+id/case_action_item_1" 
        style="@style/card_action_button" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content" /> 

       <Button 
        android:id="@+id/case_action_item_2" 
        style="@style/card_action_button" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content" /> 

      </LinearLayout> 

      <Button 
        android:id="@+id/cases_expand_button" 
        style="@style/card_action_button" 
        android:layout_height="20dp" 
        android:layout_width="20dp" 
        android:layout_alignParentEnd="true" 
        android:layout_centerVertical="true" 
        android:background="@drawable/ic_arrow" /> 

     </RelativeLayout> 
+1

'我想只有ImageView的,它WOR KS,但爲了便於使用,我需要使用Button而不是ImageView.'或使用ImageButton –

+0

謝謝Frank。我將閱讀文檔。我可以在改變圖像的同時添加動畫嗎? – kumar

+0

'ImageButton'繼承自'ImageView'。但看起來像一個'Button'。所以,如果它在'ImageView'上工作(你這麼說),它也可以在'ImageButton'上工作。 –

回答

10

最簡單的方法是將旋轉整個按鈕(和弗蘭克N.斯坦的意見建議,一個ImageButton可能是最適合的,雖然沒有什麼可以利用不同的小部件阻止你)。

有幾種方法來旋轉按鈕,但ViewPropertyAnimator又可能是最簡單的:

button.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     float deg = button.getRotation() + 180F; 
     button.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator()); 
    } 
}); 

編輯:順便說一句,如果你想箭頭扭轉其原有的動畫,你可以改爲嘗試:

float deg = (button.getRotation() == 180F) ? 0F : 180F; 

,而不是float deg = button.getRotation() + 180F;

1

您可以設置位圖作爲按鈕的背景。

Matrix matrix = new Matrix(); 

matrix.postRotate(90); 

Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true); 

Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true); 

首先從任何來源獲取位圖,然後旋轉它,然後將其設置爲按鈕中的背景。

BitmapDrawable bdrawable = new BitmapDrawable(context.getResources(),bitmap); 
button.setBackground(bdrawable);