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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With