android – 填充视图的最佳方式

我正在开发自定义布局,它具有很少的属性. Attrs:

< declare-styleable name =“CustomLayout”>
        //其他attr …
        < attr name =“data_set”format =“reference”/>
    < /声明-设置样式>

数据集只是一个字符串数组,据此我通过填充视图来填充我的布局:

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() – 这不是对多个项目执行此操作的最佳方法,不是吗?那么我应该怎么做,我应该使用基于适配器的方法吗?

最佳答案 这真的很好.它请求布局,但不会立即进行布局.它基本上向处理程序发布消息,表明需要布局.对于invalidate也是如此.因此,在UI线程返回到looper之前,不会进行实际布局.这意味着如果你连续添加一堆项目,它实际上只会布局一次.

点赞