Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to populate views

I'm developing custom layout, which has few attributes. Attrs :

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

Dataset is just a string array, according to which I fill my layout by populating views :

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);
        }
    }

Where is the best place for populating views? As I know addView() triggers requestLayout() and invalidate() - and that's not the best way to do this for multiple items, isn't it? So what should I do, should I use adapter-based approach?

like image 406
Yurii Tsap Avatar asked Oct 29 '22 19:10

Yurii Tsap


1 Answers

THats actually fine. It requests a layout, but it doesn't do the layout immediately. It basically posts a message to the handler that a layout is needed. Same for invalidate. So the actual layout won't be done until the UI thread is back in the looper. Meaning if you add a bunch of items in a row, it will only actually layout once.

like image 119
Gabe Sechan Avatar answered Nov 11 '22 20:11

Gabe Sechan