2016-07-23 48 views
0

爲什麼我的setAnimation在LongClickListener中不起作用,因爲它在LongClick偵聽器的外部正常工作?setAnimation在LongClickListener中不起作用

這是添加動畫

final Animation shake = AnimationUtils.loadAnimation(NavyashActivity.context, R.anim.shake); 
final CardView breakfast = (CardView) rootView.findViewById(R.id.breakfastcard); 
breakfast.setOnLongClickListener(new View.OnLongClickListener() { 
     @Override 
     public boolean onLongClick(View v) { 
      Log.e("shake long press","coming "); 
      // TODO Auto-generated method stub 
      breakfast.setAnimation(shake); 
      return true; 
     } 
    }); 

我的Java代碼,也是我shake.xml是:

<?xml version="1.0" encoding="utf-8"?> 
    <set xmlns:android="http://schemas.android.com/apk/res/android"> 
     <rotate 
      android:duration="70" 
      android:fromDegrees="-5" 
      android:pivotX="50%" 
      android:pivotY="50%" 
      android:repeatCount="5" 
      android:repeatMode="reverse" 
      android:interpolator="@android:anim/linear_interpolator" 
      android:toDegrees="5" /> 
     <translate 
      android:fromXDelta="-10" 
      android:toXDelta="10" 
      android:repeatCount="5" 
      android:repeatMode="reverse" 
      android:interpolator="@android:anim/linear_interpolator" 
      android:duration="70" /> 
    </set> 

和我的cardview佈局,我需要搖晃的是:

<android.support.v7.widget.CardView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="15dp" 
    android:foreground="?android:attr/selectableItemBackground" 
    android:longClickable="true" 
    android:clickable="true"  
    android:id="@+id/breakfastcard"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:background="@drawable/framebox"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:id="@+id/breakfastheading" 
      android:gravity="center_horizontal" 
      android:layout_gravity="center_horizontal" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="2dp"/> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/breakfastdetails" 
      android:layout_margin="2dp"/> 
    </LinearLayout> 
</android.support.v7.widget.CardView> 

我只是希望只要用戶長按卡片視圖元素卡應該開始晃動,以便不如果長時間觸摸它的連續移動。

回答

2

嘗試改變這一點:

breakfast.setAnimation(shake); 

要這樣:

breakfast.startAnimation(shake); 

您正在設置動畫,但不啓動它。

+0

感謝@Guilherme P的工作! –