Created
August 8, 2017 17:03
-
-
Save robillo/c54b2c68779e5475366befd60d89c3d7 to your computer and use it in GitHub Desktop.
mcv custom attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.robillo.customviewstutorial; | |
import android.content.Context; | |
import android.content.res.TypedArray; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.graphics.Paint; | |
import android.graphics.Rect; | |
import android.os.Build; | |
import android.support.annotation.Nullable; | |
import android.support.annotation.RequiresApi; | |
import android.util.AttributeSet; | |
import android.view.View; | |
/** | |
* Created by robinkamboj on 06/08/17. | |
*/ | |
public class MyCustomView extends View{ | |
Paint mPaint; | |
Rect mRect; | |
int mSquareColor; | |
public MyCustomView(Context context) { | |
super(context); | |
init(null); | |
} | |
public MyCustomView(Context context, @Nullable AttributeSet attrs) { | |
super(context, attrs); | |
init(attrs); | |
} | |
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
init(attrs); | |
} | |
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) | |
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { | |
super(context, attrs, defStyleAttr, defStyleRes); | |
init(attrs); | |
} | |
private void init(@Nullable AttributeSet set){ | |
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
mRect = new Rect(); | |
if(set == null){ | |
return; | |
} | |
TypedArray ta = getContext().obtainStyledAttributes(set, R.styleable.MyCustomView); | |
mSquareColor = ta.getColor(R.styleable.MyCustomView_square_color, Color.GREEN); | |
mPaint.setColor(mSquareColor); | |
ta.recycle(); | |
} | |
@Override | |
protected void onDraw(Canvas canvas) { | |
super.onDraw(canvas); | |
mRect.left = 0; | |
mRect.right = getWidth(); | |
mRect.top = 0; | |
mRect.bottom = getHeight(); | |
canvas.drawRect(mRect, mPaint); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment