Add custom view as a view of XML layout

前端 未结 2 1557
死守一世寂寞
死守一世寂寞 2020-12-22 03:57

The scenario is the following:

I have an activity RunTrainingWorkoutsView that uses XML layout _run_workout.xml_ with some labels that are updated by Co

2条回答
  •  天涯浪人
    2020-12-22 04:40

    Had the same issue, so I just implemented all the three constructors in the Java class of my custom view all the three constructors plus onDrow method and it worked like a charm. Try it.

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.util.AttributeSet;
    import android.view.View;
    
    public class CustomWorldWideView extends View {
    
        public CustomWorldWideView(Context context) {
    
            super(context);
        }
    
        public CustomWorldWideView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomWorldWideView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            //Some simple draw on the view...
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.parseColor("#FFA800"));
    
    
            Path path = new Path();
    
            path.moveTo(0, 0);
            path.lineTo(getWidth() / 2, 0);
            path.lineTo(getWidth(), getHeight()/2);
            path.lineTo(getWidth() / 2, getHeight());
            path.lineTo( 0, getHeight());
            path.lineTo( 0, 0);
    
            canvas.drawPath(path, paint);
    
    
        }
    }
    

    The XML :

            
    

提交回复
热议问题