2012-11-21 22 views
2

讓我們假設我們有一個簡單的LinearLayout與尺寸寬度垂直方向:100dp和高度:100dp如何在LinearLayout中隱藏部分可見視圖?

裏面的佈局有10個TextViews(寬度:FILL_PARENT,高度:WRAP_CONTENT,MAX_LINES = 1,scroll_horizo​​ntally =真,ellipsize =結束)。每個文本視圖都是可見的,並填充14dp文本「什麼是文本」。 Android設備的最終密度無關緊要。大多數的TextViews將會正確顯示,但由於強制佈局的大小,其中一些將被隱藏或剪輯。

目標是:檢測剪切後的視圖並隱藏它們。

我試過使用自定義的LinearLayout子類,在佈局階段,每個子視圖都被測量並與目標大小進行比較。問題是測量呼叫,更改內部視圖測量值 - 如果孩子不是一個簡單的視圖,但ViewGroup - 它不是正確顯示。據我所知 - 在衡量階段之後 - 應該有佈局階段。但是一切都在自定義LinearLayout的佈局階段中進行。

編輯:

OK,簡化我的問題 - 我想有一個的LinearLayout或一般來講 - 一個ViewGroup中,這不會畫部分可見的兒童。

代碼自定義佈局類:

public final class ClipAwareLinearLayout extends LinearLayout 
{  
    public ClipAwareLinearLayout(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
    } 

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

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) 
    { 
     super.onLayout(changed, l, t, r, b); 
     final int width = r - l; 
     final int height = b - t; 
     final int count = getChildCount(); 
     final int msWidth = MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST); 
     final int msHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); 
     View child; 
     int measuredHeight; 
     int childHeight; 
     for (int i = 0; i < count; ++i) 
     { 
      child = getChildAt(i); 
      if (child != null) 
      { 
       childHeight = child.getHeight(); 
       child.measure(msWidth, msHeight); 
       measuredHeight = child.getMeasuredHeight(); 
       final boolean clipped = (childHeight < measuredHeight); 
       child.setVisibility(clipped ? View.INVISIBLE : View.VISIBLE); 
      } 
     } 
    } 

}` 
+0

你想要做什麼完全?摘要你的問題,可能有一些簡單的方法來實現它.. – Snicolas

+0

通過剪輯你也意味着'TextViews'文本不適合寬度?您基本上想要顯示儘可能多的'TextViews',因爲它可能會在父'LinearLayout'的拼版維度中進行裁剪而不裁剪它們,不是嗎? – Luksprog

+0

也許我不太明白,但是,如果問題是如何理解哪些文字瀏覽是可見的,您可以計算顯示高度,並且當您添加新的textView時,可以根據文本視圖高度計算它們中的哪一個將可見或不可見。例如,顯示高度是100? TextView的高度是10?毫無疑問,10個TextViews將可見。我再說一遍,我不知道我是否理解你的問題。 – kinghomer

回答

0

嘗試下面的代碼。它應該工作,但我沒有測試,所以我可能是錯的:

class ClippedLinear extends LinearLayout { 

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

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
     boolean status = false; 
     for (int i = getChildCount() - 1; i > 0; i--) { 
      if (status) { 
       continue; 
      } 
      final View child = getChildAt(i); 
      final int childHeight = child.getMeasuredHeight(); 
      if (childHeight == 0) { 
       child.setVisibility(View.GONE);   
      } else {     
       child.measure(widthMeasureSpec, heightMeasureSpec); 
       if (childHeight < child.getMeasuredHeight()) {     
        child.setVisibility(View.GONE); 
       } 
       status = true; 
      } 
     } 
    } 

} 
相關問題