2012-05-23 47 views
2

我想創建一個自定義的View,這樣當使用wrap_content作爲尺寸參數之一併將match_parent作爲另一個參數膨脹時,它將具有恆定的寬高比,填充任何尺寸設置爲match_parent,但提供佈局充氣器與其他維度「包裝」。我認爲這是可能的,因爲,例如,全屏寬度TextView顯然能夠要求它具有用於兩個,三個或任意數量的文本行(取決於寬度)的空間,但不一定知道這一點,直到膨脹時。告訴Android佈局inflater「wrap_content」的大小應該是多大

理想情況下,我想要做的是覆蓋View子類中的佈局方法,以便當視圖膨脹時,我得到佈局信息併爲要包裝的「內容」提供我自己的尺寸(即,比例矩形)。

我需要創建很多這些自定義視圖,並將它們放入各種不同類型的佈局中(有時使用Adapter),所以我真的想對自己的通貨膨脹有最大限度的控制。這樣做最好的技術是什麼?

回答

0

我現在用下面的代碼解決了這個。值得一提的是,我最重要的課程是自定義ViewGroup自定義子項,全部使用繼承的onMeasure。孩子們在建造時被創造和補充,當然我認爲這是必要的。

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    float width = MeasureSpec.getSize(widthMeasureSpec); 
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec); 

    float height = MeasureSpec.getSize(heightMeasureSpec); 
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 

    float nominalHeight = getResources().getInteger(R.integer.nominalheight); 
    float nominalWidth = getResources().getInteger(R.integer.nominalwidth); 

    float aspectRatio = nominalWidth/nominalHeight; 

    if(widthMode == MeasureSpec.UNSPECIFIED) { //conform width to height 
     width = height * aspectRatio; 
    } 
    else if (heightMode == MeasureSpec.UNSPECIFIED) { //conform height to width 
     height = width/aspectRatio; 
    } 
    else if(width/height > aspectRatio //too wide 
      && (widthMode == MeasureSpec.AT_MOST) 
      ) { 
     width -= (width - height * aspectRatio); 
    } 
    else if(width/height < aspectRatio //too tall 
      && (heightMode == MeasureSpec.AT_MOST) 
      ) { 
     height -= (height - width/aspectRatio); 
    } 

    int newWidthMeasure = MeasureSpec.makeMeasureSpec((int)width, MeasureSpec.AT_MOST); 
    int newHeightMeasure = MeasureSpec.makeMeasureSpec((int)height, MeasureSpec.AT_MOST); 
    measureChildren(newWidthMeasure, newHeightMeasure); 

    setMeasuredDimension((int)width, (int)height); 
} 

我用資源中名義矩形來定義縱橫比,但顯然還有很多其他方法可以做到這一點。

感謝Josephus Villarey誰指我在onMeasure(...)首先。

1

您可以隨時檢查onMeasure是否符合寬高比。

不是一個完整的答案,我知道,但它應該引領你在那裏;)

+0

謝謝,這真的很有用:) –

+0

我已經把我的實現作爲答案,但提示是讓我在那裏的步驟 - 再次感謝! –