填充视图的最佳方式

Yur*_*sap 5 performance android

我正在开发自定义布局,它的属性很少。属性:

<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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

填充视图的最佳位置在哪里?据我所知, addView() 会触发 requestLayout() 和 invalidate() - 这不是对多个项目执行此操作的最佳方法,不是吗?那么我应该怎么做,我应该使用基于适配器的方法吗?

Gab*_*han 2

这实际上很好。它请求布局,但不会立即进行布局。它基本上向处理程序发送一条消息,表明需要布局。无效也一样。因此,直到 UI 线程返回循环程序后,实际布局才会完成。这意味着如果您连续添加一堆项目,它实际上只会布局一次。