Stan
Stan

Reputation: 6561

How to optimize custom view?

So I defined an custom view based on LinearLayout:

    public class AlphabetButton extends LinearLayout{

        private Button alphabetButton;
        private ImageView usersMark;
...     
        public AlphabetButton(Context context) {
            super(context);
            load(context);
        }
...    
        private void load(Context context){
            if(isInEditMode()) 
                return;

            LayoutInflater.from(context).inflate(R.layout.alphabet_button, this, true);

            alphabetButton = (Button)findViewById(R.id.buttonAlphabetItem);
            usersMark = (ImageView)findViewById(R.id.correctWrongSelectedMark);

            alphabetButton.setTag(usersMark);

            final Typeface chalkFont = Typeface.createFromAsset(context.getAssets(), "fonts/myfont.ttf");
            alphabetButton.setTypeface(chalkFont);

        }

since app creates about 30 pcs of this view it has a noticeable lag (on weak CPU smartphones it takes about 2-3s) . I also noticed a log output (not mine) like:

05-01 16:47:22.224: D/szipinf(10569): Initializing inflate state
05-01 16:47:22.234: D/szipinf(10569): Initializing inflate state
05-01 16:47:22.254: D/szipinf(10569): Initializing inflate state
05-01 16:47:22.264: D/szipinf(10569): Initializing inflate state
05-01 16:47:22.334: D/szipinf(10569): Initializing inflate state

and there are about 30 same lines. So I assume that load(Context context) method and especially inflating process is the resource of lags. But how to avoid it? How to optimize this view to instantiate it faster?

Upvotes: 1

Views: 715

Answers (1)

baske
baske

Reputation: 1352

I don't think you can inflate a View and then cache it for future use (i.e. the second time you enter the constructor), because you will get errors like "view already has a parent". However, I don't know if the same holds for the Typeface you inflate.. maybe that one IS reusable.

Furthermore: I don't know if your R.layout.alphabet_button contains a lot if images? If that is the case you may want to get rid of a few of those, in favor of xml-generated graphics, like using xml shapes/gradients etc. In my experience, those load a LOT faster. If you cannot get rid of your images, you may at least be able to load those once and then copy them in-memory instead of inflating them each time (so don't put them in your layout.xml, but set them on your ImageView afterwards with methods like setImageBitmap() or setImageDrawable().

As always with these kind of caching tricks: be sure to check your app for memory leaks ;-)

Upvotes: 1

Related Questions