Setting color of a Paint object in custom view

前端 未结 2 1748
清酒与你
清酒与你 2020-12-06 07:04

I am trying to make a custom view and have declared the styled attributes like the below:-

  
 

        
2条回答
  •  爱一瞬间的悲伤
    2020-12-06 07:55

    In colors.xml

    
    
        #000000
    
    

    To retrieve

    Resources res = getResources();
    int color = res.getColor(R.color.black_color);
    

    Then set color to paint

    thePaintObj.setColor(color);
    

    More info @

    http://developer.android.com/guide/topics/resources/more-resources.html#Color

    Edit:

    MyCustomView

    public class CustomView extends View{
    
        Paint p;
        int color ;
        public CustomView(Context context) {
            this(context, null);
        }
    
        public CustomView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public CustomView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            // real work here
            TypedArray a = context.getTheme().obtainStyledAttributes(
                    attrs,
                    R.styleable.NewCircleView,
                    0, 0
            );
    
            try {
    
             color = a.getColor(R.styleable.NewCircleView_circlecolor, 0xff000000);
            } finally {
                // release the TypedArray so that it can be reused.
                a.recycle();
            }
            init();
        }
    
    public void init()
    {
          p = new Paint();
          p.setColor(color);
    }
    
        @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);
            if(canvas!=null)
            {
            canvas.drawCircle(100, 100,30,p );
            }
        }
    
    }
    

    attrs.xml

    
    
         
        
        
    
    
    

    colors.xml

    
    
        #000000
    
    

    MyCustomView in xml

    
    

    Snap Shot

    enter image description here

提交回复
热议问题