“requestLayout() improperly called by…” error on Android 4.3

前端 未结 5 2293
一个人的身影
一个人的身影 2020-12-30 21:57

I have a simple Custom TextView that sets custom font in its constructor like the code below

public class MyTextView extends TextView {

    @Inject CustomTy         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 22:33

    I fixed these warnings in my custom ListView item (LinearLayout subclass). This class implements Checkable, and has a setChecked(boolean checked) method that is called to indicate whether the item is checked:

    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        TextView textView = (TextView)this.findViewById(R.id.drawer_list_item_title_text_view);
        if(mChecked) {
            textView.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "font/Andada-Bold.ttf"));
        }
        else {
            textView.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "font/Andada-Regular.ttf"));
        }
    }
    

    I visually indicate the checked state by calling setTypeFace() on a textView in my view, toggling between regular and bold typefaces. These setTypeFace() calls were causing the warnings.

    To fix the problem, I created instance variables for the Typefaces in the class constructor and used them later, when changing the typeface, rather than calling Typeface.createFromAsset(...) every time:

    private Typeface mBoldTypeface;
    private Typeface mRegularTypeface;
    
    public DrawerView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initTypefaces();
    }
    
    private void initTypefaces() {
            this.mBoldTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Andada-Bold.ttf");
            this.mRegularTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/Andada-Regular.ttf");
    }
    
    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        TextView textView = (TextView)this.findViewById(R.id.drawer_list_item_title_text_view);
        if(mChecked) {
            textView.setTypeface(mBoldTypeface);
        }
        else {
            textView.setTypeface(mRegularTypeface);
        }
    }
    

    This is a pretty specific scenario, but I was pleasantly surprised to find a fix and maybe someone else is in the same situation.

提交回复
热议问题