2017-07-10 238 views
0

我正在致力於在CardView上展開和收縮屬性。CardView的可擴展高度

public class SimpleCardView extends CardView { 
private int animationDuration; 


    public SimpleCardView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    public SimpleCardView(Context context) { 
     super(context); 
    } 

    public SimpleCardView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public void expand(){ 
     final int initialHeight = getHeight(); 
     final float scale = getContext().getResources().getDisplayMetrics().density; 
     int targetHeight = (int) (232 * scale + 0.5f); 
     final int distance_to_expand = targetHeight - initialHeight; 
     Animation animation = new Animation() { 
      @Override 
      protected void applyTransformation(float interpolatedTime, Transformation t) { 
       getLayoutParams().height = (int) (initialHeight +(distance_to_expand*interpolatedTime)); 
       requestLayout(); 
      } 

      @Override 
      public boolean willChangeBounds() { 
       return true; 
      } 
     }; 
     animationDuration = distance_to_expand; 
     animation.setDuration((long)distance_to_expand); 
     startAnimation(animation); 
    } 

    public int getAnimationTime(){ 
     return animationDuration; 
    } 

    public void collapse(){} 

} 

這是我的截圖:

enter image description here

我設定目標高度的恆定值。

int targetHeight = (int) (232 * scale + 0.5f); 

這裏,targetHeightCardView一個膨脹高度。 因此,當內容太長時,只顯示少部分內容。

有什麼辦法來動態設置高度不是一個常數值嗎?

+0

簡單的解決方案兄弟。設置CardView高度wrap_content setYour標題當你做和下面的TextView內容可見性應該消失。所以當你點擊展開只是試圖看到包含內容的TextView。 –

+0

讓視圖可見性可見/消失是個好主意。現在我不這樣做。那麼,有什麼辦法可以動態地達到目標高度。 –

回答

0

你有沒有試過用:WRAP_CONTENT

android:layout_height="wrap_content" 

<android.support.v7.widget.CardView 
android:id="@+id/cardView" 
android:layout_width="match_parent" 
android:layout_height="wrap_content"> 

而且你需要刪除靜態高度窗體類SimpleCardView

**,或者你需要計算身高**

爲此,您需要設置文成TextView後的TextView低於線,然後 計算高度進入SimpleCardView通過使任何setter方法。

TextView textview ; 

textveiw.setText("your text"); 
textview.mesure(0,0); 
int height = textview.getMesuredHeight(); 
+0

是的,我已經有了那個。 –

+0

這工作? –

+0

有沒有什麼辦法可以將SimpleCardView類中的高度動態地設置爲'WRAP_CONTENT'。 –