my Custom View gets drawn only when added in onCreate

后端 未结 1 528
南旧
南旧 2020-12-12 06:18

I made a \"GraphBar\" custom view that is a RelativeLayout with a TextView on the bottom and an ImageView, varying in height, above th

相关标签:
1条回答
  • 2020-12-12 06:31

    I've finally found a way to call again requestLayout(). I called setWillNotDraw(false) in the constructor so that in onDraw() (that is after onLayout()) I can call the extra requestLayout(). This generates a stupid cycle but solves the problem aesthetically.

    If anyone knows a better solution, let me know... here the new code (modifies are next to comments):

    //...
        public GraphBar(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            LayoutInflater.from(context).inflate(R.layout.graphbar, this, true);
            setWillNotDraw(false); // WORKAROUND: onDraw will be used to make the
                                    // redundant requestLayout() call
            setId(R.id.graphBar);
        }
    //...
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            // i think it's one of the worst workaround one could think of.
            // luckily android is smart enough to stop the cycle...
            findViewById(R.id.smallBar).requestLayout();
        }
    
        public void setBarHeight(float value, float max) {
            mBarHeight = value / max;
            View bar =   findViewById(R.id.smallBar);
    
            bar.requestLayout(); // because when we create this view onDraw is called...
            bar.invalidate();    // ...but not when we modify it!!!
                                //so we need to invalidate too
        }
    //...
    
    0 讨论(0)
提交回复
热议问题