2016-09-27 107 views
4

我正在開發自定義佈局,它具有很少的屬性。 ATTRS:填充視圖的最佳方法

<declare-styleable name="CustomLayout"> //other attr... <attr name="data_set" format="reference"/> </declare-styleable>

數據集只是一個字符串數組,根據我通過填充觀點填補我的佈局:

private Option[] mOptions; // just an array for filing content 

public CustomLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
    TypedArray array = context 
      .obtainStyledAttributes(attrs, R.styleable.CustomLayout); 
    int arrayId = array.getResourceId(R.styleable._data_set, -1); 
    if (arrayId != -1) { 
     array = getResources().obtainTypedArray(arrayId); 
     mOptions = new Option[array.length()]; 
     for (int index = 0; index < array.length(); index++) { 
      mOptions[index] = new Option(); 
      mOptions[index].setLabel(array.getString(index)); 
     } 
     populateViews(); 
    } 

    array.recycle(); 
} 

private void populateViews() { 
    if (mOptions.length > 0) { 
     for (int index = 0; index < mOptions.length; index++) { 
      final Option option = mOptions[index]; 
      TextView someTextView = (TextView) LayoutInflater.from(getContext()) 
        .inflate(R.layout.some_layout, this, false); 
      //other initialization stuff 
      addView(someTextView); 
     } 
    } 

哪裏是用於填充意見的最佳地點?正如我所知addView()觸發requestLayout()和invalidate() - 這不是多個項目這樣做的最好方法,不是嗎?那麼我應該怎麼做,我應該使用基於適配器的方法?

回答

2

其實很好。它請求佈局,但不會立即執行佈局。它基本上向消息處理器發佈消息,需要佈局。相同的無效。所以直到UI線程回到Looper中,實際的佈局纔會完成。意思是如果你在一行中添加一堆項目,它只會實際佈局一次。

+0

因此,即使我將實現類似ListView的東西,我將在view的內部獲取onMeasure() - 這不會優化我當前的實現嗎?或者,也許你可以推薦其他方法? –

相關問題