Error while while opening an activity - android

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.applexus.PROJMANAGER/com.applexus.PROJMANAGER.CalendarType}:
android.view.InflateException: Binary XML file line #60: Error inflating class
com.applexus.Scheduler.CalendarView
I get this error when clicking my Calendar activity.
This is a calender view which am using in my activity and I
get the error while opening the activity. Here is the code:
public class CalendarView extends ImageView {
private static int WEEK_TOP_MARGIN = 74;
private static int WEEK_LEFT_MARGIN = 40;
private static int CELL_WIDTH = 58;
private static int CELL_HEIGH = 53;
private static int CELL_MARGIN_TOP = 92;
private static int CELL_MARGIN_LEFT = 39;
private static float CELL_TEXT_SIZE;
private static final String TAG = "CalendarView";
private Calendar mRightNow = null;
private Drawable mWeekTitle = null;
private Cell mToday = null;
private Cell[][] mCells = new Cell[6][7];
private OnCellTouchListener mOnCellTouchListener = null;
MonthDisplayHelper mHelper;
Drawable mDecoration = null;
public interface OnCellTouchListener {
public void onTouch(Cell cell);
}
public CalendarView(Context context) {
this(context, null);
}
public CalendarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CalendarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDecoration = context.getResources().getDrawable(R.drawable.typeb_calendar_today);
initCalendarView();
}
private void initCalendarView() {
mRightNow = Calendar.getInstance();
// prepare static vars
Resources res = getResources();
WEEK_TOP_MARGIN = (int) res.getDimension(R.dimen.week_top_margin);
WEEK_LEFT_MARGIN = (int) res.getDimension(R.dimen.week_left_margin);
CELL_WIDTH = (int) res.getDimension(R.dimen.cell_width);
CELL_HEIGH = (int) res.getDimension(R.dimen.cell_heigh);
CELL_MARGIN_TOP = (int) res.getDimension(R.dimen.cell_margin_top);
CELL_MARGIN_LEFT = (int) res.getDimension(R.dimen.cell_margin_left);
CELL_TEXT_SIZE = res.getDimension(R.dimen.cell_text_size);
// set background
setImageResource(R.drawable.background);
mWeekTitle = res.getDrawable(R.drawable.calendar_week);
mHelper = new MonthDisplayHelper(mRightNow.get(Calendar.YEAR), mRightNow.get(Calendar.MONTH));
}
private void initCells() {
class _calendar {
public int day;
public boolean thisMonth;
public _calendar(int d, boolean b) {
day = d;
thisMonth = b;
}
public _calendar(int d) {
this(d, false);
}
};
_calendar tmp[][] = new _calendar[6][7];
for(int i=0; i<tmp.length; i++) {
int n[] = mHelper.getDigitsForRow(i);
for(int d=0; d<n.length; d++) {
if(mHelper.isWithinCurrentMonth(i,d))
tmp[i][d] = new _calendar(n[d], true);
else
tmp[i][d] = new _calendar(n[d]);
}
}
Calendar today = Calendar.getInstance();
int thisDay = 0;
mToday = null;
if(mHelper.getYear()==today.get(Calendar.YEAR) && mHelper.getMonth()==today.get(Calendar.MONTH)) {
thisDay = today.get(Calendar.DAY_OF_MONTH);
}
// build cells
Rect Bound = new Rect(CELL_MARGIN_LEFT, CELL_MARGIN_TOP, CELL_WIDTH+CELL_MARGIN_LEFT, CELL_HEIGH+CELL_MARGIN_TOP);
for(int week=0; week<mCells.length; week++) {
for(int day=0; day<mCells[week].length; day++) {
if(tmp[week][day].thisMonth) {
if(day==0 || day==6 )
mCells[week][day] = new RedCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
else
mCells[week][day] = new Cell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
} else {
mCells[week][day] = new GrayCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
}
Bound.offset(CELL_WIDTH, 0); // move to next column
// get today
if(tmp[week][day].day==thisDay && tmp[week][day].thisMonth) {
mToday = mCells[week][day];
mDecoration.setBounds(mToday.getBound());
}
}
Bound.offset(0, CELL_HEIGH); // move to next row and first column
Bound.left = CELL_MARGIN_LEFT;
Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
}
}
#Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
Rect re = getDrawable().getBounds();
WEEK_LEFT_MARGIN = CELL_MARGIN_LEFT = (right-left - re.width()) / 2;
mWeekTitle.setBounds(WEEK_LEFT_MARGIN, WEEK_TOP_MARGIN, WEEK_LEFT_MARGIN+mWeekTitle.getMinimumWidth(), WEEK_TOP_MARGIN+mWeekTitle.getMinimumHeight());
initCells();
super.onLayout(changed, left, top, right, bottom);
}
public void setTimeInMillis(long milliseconds) {
mRightNow.setTimeInMillis(milliseconds);
initCells();
this.invalidate();
}
public int getYear() {
return mHelper.getYear();
}
public int getMonth() {
return mHelper.getMonth();
}
public void nextMonth() {
mHelper.nextMonth();
initCells();
invalidate();
}
public void previousMonth() {
mHelper.previousMonth();
initCells();
invalidate();
}
public boolean firstDay(int day) {
return day==1;
}
public boolean lastDay(int day) {
return mHelper.getNumberOfDaysInMonth()==day;
}
public void goToday() {
Calendar cal = Calendar.getInstance();
mHelper = new MonthDisplayHelper(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH));
initCells();
invalidate();
}
public Calendar getDate() {
return mRightNow;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(mOnCellTouchListener!=null){
for(Cell[] week : mCells) {
for(Cell day : week) {
if(day.hitTest((int)event.getX(), (int)event.getY())) {
mOnCellTouchListener.onTouch(day);
}
}
}
}
return super.onTouchEvent(event);
}
public void setOnCellTouchListener(OnCellTouchListener p) {
mOnCellTouchListener = p;
}
#Override
protected void onDraw(Canvas canvas) {
// draw background
super.onDraw(canvas);
mWeekTitle.draw(canvas);
// draw cells
for(Cell[] week : mCells) {
for(Cell day : week) {
day.draw(canvas);
}
}
// draw today
if(mDecoration!=null && mToday!=null) {
mDecoration.draw(canvas);
}
}
public class GrayCell extends Cell {
public GrayCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(Color.LTGRAY);
}
}
private class RedCell extends Cell {
public RedCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(0xdddd0000);
}
}
}

Did you checked the xml file? Is there are problems with that? Your log says inflate exception, so I think it probably caused by your xml layout or something wrong with the inflating process. you can post your activity's source code here, and we will see what we can do to help

Related

Android LuckyWheel Library add onClick method on Canvas item

I am using this library to draw a circle with eight equal triangular parts and rotate them. Now I want to add an OnClick feature, so when user clicks on one of the triangles it will rotate to the selected position. This library already has code for rotating an item by it's index, but I cannot figure out how to find the index of the triangle which has been clicked. Has anyone worked with this before? Any help is appreciated.
Code:
LuckyWheelView.java
public class LuckyWheelView extends RelativeLayout implements PielView.PieRotateListener {
private int mBackgroundColor;
private int mTextColor;
private int mTopTextSize;
private int mSecondaryTextSize;
private int mBorderColor;
private int mTopTextPadding;
private int mEdgeWidth;
private Drawable mCenterImage;
private Drawable mCursorImage;
private PielView pielView;
private ImageView ivCursorView;
private LuckyRoundItemSelectedListener mLuckyRoundItemSelectedListener;
#Override
public void rotateDone(int index) {
if (mLuckyRoundItemSelectedListener != null) {
mLuckyRoundItemSelectedListener.LuckyRoundItemSelected(index);
}
}
public interface LuckyRoundItemSelectedListener {
void LuckyRoundItemSelected(int index);
}
public void setLuckyRoundItemSelectedListener(LuckyRoundItemSelectedListener listener) {
this.mLuckyRoundItemSelectedListener = listener;
}
public LuckyWheelView(Context context) {
super(context);
init(context, null);
}
public LuckyWheelView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
/**
* #param ctx
* #param attrs
*/
private void init(Context ctx, AttributeSet attrs) {
if (attrs != null) {
TypedArray typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.LuckyWheelView);
mBackgroundColor = typedArray.getColor(R.styleable.LuckyWheelView_lkwBackgroundColor, 0xffcc0000);
mTopTextSize = typedArray.getDimensionPixelSize(R.styleable.LuckyWheelView_lkwTopTextSize, (int) LuckyWheelUtils.convertDpToPixel(10f, getContext()));
mSecondaryTextSize = typedArray.getDimensionPixelSize(R.styleable.LuckyWheelView_lkwSecondaryTextSize, (int) LuckyWheelUtils.convertDpToPixel(20f, getContext()));
mTextColor = typedArray.getColor(R.styleable.LuckyWheelView_lkwTopTextColor, 0);
mTopTextPadding = typedArray.getDimensionPixelSize(R.styleable.LuckyWheelView_lkwTopTextPadding, (int) LuckyWheelUtils.convertDpToPixel(10f, getContext())) + (int) LuckyWheelUtils.convertDpToPixel(10f, getContext());
mCursorImage = typedArray.getDrawable(R.styleable.LuckyWheelView_lkwCursor);
mCenterImage = typedArray.getDrawable(R.styleable.LuckyWheelView_lkwCenterImage);
mEdgeWidth = typedArray.getInt(R.styleable.LuckyWheelView_lkwEdgeWidth, 10);
mBorderColor = typedArray.getColor(R.styleable.LuckyWheelView_lkwEdgeColor, 0);
typedArray.recycle();
}
LayoutInflater inflater = LayoutInflater.from(getContext());
FrameLayout frameLayout = (FrameLayout) inflater.inflate(R.layout.lucky_wheel_layout, this, false);
pielView = frameLayout.findViewById(R.id.pieView);
ivCursorView = frameLayout.findViewById(R.id.cursorView);
pielView.setPieRotateListener(this);
pielView.setPieBackgroundColor(mBackgroundColor);
pielView.setTopTextPadding(mTopTextPadding);
pielView.setTopTextSize(mTopTextSize);
pielView.setSecondaryTextSizeSize(mSecondaryTextSize);
pielView.setPieCenterImage(mCenterImage);
pielView.setBorderColor(mBorderColor);
pielView.setBorderWidth(mEdgeWidth);
if (mTextColor != 0)
pielView.setPieTextColor(mTextColor);
ivCursorView.setImageDrawable(mCursorImage);
addView(frameLayout);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//This is to control that the touch events triggered are only going to the PieView
for (int i = 0; i < getChildCount(); i++) {
if (isPielView(getChildAt(i))) {
return super.dispatchTouchEvent(ev);
}
}
return false;
}
private boolean isPielView(View view) {
if (view instanceof ViewGroup) {
for (int i = 0; i < getChildCount(); i++) {
if (isPielView(((ViewGroup) view).getChildAt(i))) {
return true;
}
}
}
return view instanceof PielView;
}
public void setLuckyWheelBackgrouldColor(int color) {
pielView.setPieBackgroundColor(color);
}
public void setLuckyWheelCursorImage(int drawable) {
ivCursorView.setBackgroundResource(drawable);
}
public void setLuckyWheelCenterImage(Drawable drawable) {
pielView.setPieCenterImage(drawable);
}
public void setBorderColor(int color) {
pielView.setBorderColor(color);
}
public void setLuckyWheelTextColor(int color) {
pielView.setPieTextColor(color);
}
/**
* #param data
*/
public void setData(List<LuckyItem> data) {
pielView.setData(data);
}
/**
* #param numberOfRound
*/
public void setRound(int numberOfRound) {
pielView.setRound(numberOfRound);
}
/**
* #param fixedNumber
*/
public void setPredeterminedNumber(int fixedNumber) {
pielView.setPredeterminedNumber(fixedNumber);
}
public void startLuckyWheelWithTargetIndex(int index) {
pielView.rotateTo(index);
}
}
MainActivity.java
public class MainActivity extends Activity {
List<LuckyItem> data = new ArrayList<>();
LuckyWheelView luckyWheelView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
luckyWheelView = (LuckyWheelView) findViewById(R.id.luckyWheel);
LuckyItem luckyItem1 = new LuckyItem();
/*luckyItem1.topText = "100";
luckyItem1.icon = R.drawable.test1;*/
luckyItem1.color = 0xffFFF3E0;
data.add(luckyItem1);
LuckyItem luckyItem2 = new LuckyItem();
/*luckyItem2.topText = "200";
luckyItem2.icon = R.drawable.test2;*/
luckyItem2.color = 0xffFFE0B2;
data.add(luckyItem2);
LuckyItem luckyItem3 = new LuckyItem();
/*uckyItem3.topText = "300";
luckyItem3.icon = R.drawable.test3;*/
luckyItem3.color = 0xffFFCC80;
data.add(luckyItem3);
//////////////////
final LuckyItem luckyItem4 = new LuckyItem();
/*luckyItem4.topText = "400";
luckyItem4.icon = R.drawable.test4;*/
luckyItem4.color = 0xffFFF3E0;
data.add(luckyItem4);
LuckyItem luckyItem5 = new LuckyItem();
/*luckyItem5.topText = "500";
luckyItem5.icon = R.drawable.test5;*/
luckyItem5.color = 0xffFFE0B2;
data.add(luckyItem5);
LuckyItem luckyItem6 = new LuckyItem();
/*luckyItem6.topText = "600";
luckyItem6.icon = R.drawable.test6;*/
luckyItem6.color = 0xffFFCC80;
data.add(luckyItem6);
//////////////////
//////////////////////
LuckyItem luckyItem7 = new LuckyItem();
/*luckyItem7.topText = "700";
luckyItem7.icon = R.drawable.test7;*/
luckyItem7.color = 0xffFFF3E0;
data.add(luckyItem7);
LuckyItem luckyItem8 = new LuckyItem();
/*luckyItem8.topText = "800";
luckyItem8.icon = R.drawable.test8;*/
luckyItem8.color = 0xffFFE0B2;
data.add(luckyItem8);
/////////////////////
luckyWheelView.setData(data);
luckyWheelView.setRound(0);
luckyWheelView.setLuckyRoundItemSelectedListener(new LuckyWheelView.LuckyRoundItemSelectedListener() {
#Override
public void LuckyRoundItemSelected(int index) {
// Toast.makeText(getApplicationContext(), data.get(index).topText, Toast.LENGTH_SHORT).show();
}
});
}
}

how to change the shape of the button from rounded rectangle to circle using animation

I have a rounded rectangle button in my activity. Once I click the button, it should slightly compress/shrink (height of the button should not change) and it should change to a circle shape. How can I achieve this using the anim folder in XML?
Currently my code is:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="400"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:toXScale="0.1"
android:toYScale="1" />
<set>
<alpha
android:duration="400"
android:fromAlpha="1"
android:toAlpha="0" />
</set>
</set>
Create MorphingButton class paste below code into;
public class MorphingButton extends Button {
private Padding mPadding;
private int mHeight;
private int mWidth;
private int mColor;
private int mCornerRadius;
private int mStrokeWidth;
private int mStrokeColor;
protected boolean mAnimationInProgress;
private StrokeGradientDrawable mDrawableNormal;
private StrokeGradientDrawable mDrawablePressed;
public MorphingButton(Context context) {
super(context);
initView();
}
public MorphingButton(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public MorphingButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mHeight == 0 && mWidth == 0 && w != 0 && h != 0) {
mHeight = getHeight();
mWidth = getWidth();
}
}
public StrokeGradientDrawable getDrawableNormal() {
return mDrawableNormal;
}
public void morph(#NonNull Params params) {
if (!mAnimationInProgress) {
mDrawablePressed.setColor(params.colorPressed);
mDrawablePressed.setCornerRadius(params.cornerRadius);
mDrawablePressed.setStrokeColor(params.strokeColor);
mDrawablePressed.setStrokeWidth(params.strokeWidth);
if (params.duration == 0) {
morphWithoutAnimation(params);
} else {
morphWithAnimation(params);
}
mColor = params.color;
mCornerRadius = params.cornerRadius;
mStrokeWidth = params.strokeWidth;
mStrokeColor = params.strokeColor;
}
}
private void morphWithAnimation(#NonNull final Params params) {
mAnimationInProgress = true;
setText(null);
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
setPadding(mPadding.left, mPadding.top, mPadding.right, mPadding.bottom);
MorphingAnimation.Params animationParams = MorphingAnimation.Params.create(this)
.color(mColor, params.color)
.cornerRadius(mCornerRadius, params.cornerRadius)
.strokeWidth(mStrokeWidth, params.strokeWidth)
.strokeColor(mStrokeColor, params.strokeColor)
.height(getHeight(), params.height)
.width(getWidth(), params.width)
.duration(params.duration)
.listener(new MorphingAnimation.Listener() {
#Override
public void onAnimationEnd() {
finalizeMorphing(params);
}
});
MorphingAnimation animation = new MorphingAnimation(animationParams);
animation.start();
}
private void morphWithoutAnimation(#NonNull Params params) {
mDrawableNormal.setColor(params.color);
mDrawableNormal.setCornerRadius(params.cornerRadius);
mDrawableNormal.setStrokeColor(params.strokeColor);
mDrawableNormal.setStrokeWidth(params.strokeWidth);
if(params.width != 0 && params.height !=0) {
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width = params.width;
layoutParams.height = params.height;
setLayoutParams(layoutParams);
}
finalizeMorphing(params);
}
private void finalizeMorphing(#NonNull Params params) {
mAnimationInProgress = false;
if (params.icon != 0 && params.text != null) {
setIconLeft(params.icon);
setText(params.text);
} else if (params.icon != 0) {
setIcon(params.icon);
} else if(params.text != null) {
setText(params.text);
}
if (params.animationListener != null) {
params.animationListener.onAnimationEnd();
}
}
public void blockTouch() {
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
public void unblockTouch() {
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
}
private void initView() {
mPadding = new Padding();
mPadding.left = getPaddingLeft();
mPadding.right = getPaddingRight();
mPadding.top = getPaddingTop();
mPadding.bottom = getPaddingBottom();
Resources resources = getResources();
int cornerRadius = (int) resources.getDimension(R.dimen._10sdp);
int primaryColor = resources.getColor(R.color.colorAccent);
int secondaryColor = resources.getColor(R.color.colorPrimary);
StateListDrawable background = new StateListDrawable();
mDrawableNormal = createDrawable(primaryColor, cornerRadius, 0);
mDrawablePressed = createDrawable(secondaryColor, cornerRadius, 0);
mColor = primaryColor;
mStrokeColor = primaryColor;
mCornerRadius = cornerRadius;
background.addState(new int[]{android.R.attr.state_pressed}, mDrawablePressed.getGradientDrawable());
background.addState(StateSet.WILD_CARD, mDrawableNormal.getGradientDrawable());
setBackgroundCompat(background);
}
private StrokeGradientDrawable createDrawable(int color, int cornerRadius, int strokeWidth) {
StrokeGradientDrawable drawable = new StrokeGradientDrawable(new GradientDrawable());
drawable.getGradientDrawable().setShape(GradientDrawable.RECTANGLE);
drawable.setColor(color);
drawable.setCornerRadius(cornerRadius);
drawable.setStrokeColor(color);
drawable.setStrokeWidth(strokeWidth);
return drawable;
}
#SuppressWarnings("deprecation")
private void setBackgroundCompat(#Nullable Drawable drawable) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
setBackgroundDrawable(drawable);
} else {
setBackground(drawable);
}
}
public void setIcon(#DrawableRes final int icon) {
// post is necessary, to make sure getWidth() doesn't return 0
post(new Runnable() {
#Override
public void run() {
Drawable drawable = getResources().getDrawable(icon);
int padding = (getWidth() / 2) - (drawable.getIntrinsicWidth() / 2);
setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
setPadding(padding, 0, 0, 0);
}
});
}
public void setIconLeft(#DrawableRes int icon) {
setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
}
private class Padding {
public int left;
public int right;
public int top;
public int bottom;
}
public static class Params {
private int cornerRadius;
private int width;
private int height;
private int color;
private int colorPressed;
private int duration;
private int icon;
private int strokeWidth;
private int strokeColor;
private String text;
private MorphingAnimation.Listener animationListener;
private Params() {
}
public static Params create() {
return new Params();
}
public Params text(#NonNull String text) {
this.text = text;
return this;
}
public Params icon(#DrawableRes int icon) {
this.icon = icon;
return this;
}
public Params cornerRadius(int cornerRadius) {
this.cornerRadius = cornerRadius;
return this;
}
public Params width(int width) {
this.width = width;
return this;
}
public Params height(int height) {
this.height = height;
return this;
}
public Params color(int color) {
this.color = color;
return this;
}
public Params colorPressed(int colorPressed) {
this.colorPressed = colorPressed;
return this;
}
public Params duration(int duration) {
this.duration = duration;
return this;
}
public Params strokeWidth(int strokeWidth) {
this.strokeWidth = strokeWidth;
return this;
}
public Params strokeColor(int strokeColor) {
this.strokeColor = strokeColor;
return this;
}
public Params animationListener(MorphingAnimation.Listener animationListener) {
this.animationListener = animationListener;
return this;
}
}
public static class MorphingAnimation {
public interface Listener {
void onAnimationEnd();
}
public static class Params {
private float fromCornerRadius;
private float toCornerRadius;
private int fromHeight;
private int toHeight;
private int fromWidth;
private int toWidth;
private int fromColor;
private int toColor;
private int duration;
private int fromStrokeWidth;
private int toStrokeWidth;
private int fromStrokeColor;
private int toStrokeColor;
private MorphingButton button;
private MorphingAnimation.Listener animationListener;
private Params(#NonNull MorphingButton button) {
this.button = button;
}
public static Params create(#NonNull MorphingButton button) {
return new Params(button);
}
public Params duration(int duration) {
this.duration = duration;
return this;
}
public Params listener(#NonNull MorphingAnimation.Listener animationListener) {
this.animationListener = animationListener;
return this;
}
public Params color(int fromColor, int toColor) {
this.fromColor = fromColor;
this.toColor = toColor;
return this;
}
public Params cornerRadius(int fromCornerRadius, int toCornerRadius) {
this.fromCornerRadius = fromCornerRadius;
this.toCornerRadius = toCornerRadius;
return this;
}
public Params height(int fromHeight, int toHeight) {
this.fromHeight = fromHeight;
this.toHeight = toHeight;
return this;
}
public Params width(int fromWidth, int toWidth) {
this.fromWidth = fromWidth;
this.toWidth = toWidth;
return this;
}
public Params strokeWidth(int fromStrokeWidth, int toStrokeWidth) {
this.fromStrokeWidth = fromStrokeWidth;
this.toStrokeWidth = toStrokeWidth;
return this;
}
public Params strokeColor(int fromStrokeColor, int toStrokeColor) {
this.fromStrokeColor = fromStrokeColor;
this.toStrokeColor = toStrokeColor;
return this;
}
}
private Params mParams;
public MorphingAnimation(#NonNull Params params) {
mParams = params;
}
public void start() {
StrokeGradientDrawable background = mParams.button.getDrawableNormal();
ObjectAnimator cornerAnimation =
ObjectAnimator.ofFloat(background, "cornerRadius", mParams.fromCornerRadius, mParams.toCornerRadius);
ObjectAnimator strokeWidthAnimation =
ObjectAnimator.ofInt(background, "strokeWidth", mParams.fromStrokeWidth, mParams.toStrokeWidth);
ObjectAnimator strokeColorAnimation = ObjectAnimator.ofInt(background, "strokeColor", mParams.fromStrokeColor, mParams.toStrokeColor);
strokeColorAnimation.setEvaluator(new ArgbEvaluator());
ObjectAnimator bgColorAnimation = ObjectAnimator.ofInt(background, "color", mParams.fromColor, mParams.toColor);
bgColorAnimation.setEvaluator(new ArgbEvaluator());
ValueAnimator heightAnimation = ValueAnimator.ofInt(mParams.fromHeight, mParams.toHeight);
heightAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int val = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mParams.button.getLayoutParams();
layoutParams.height = val;
mParams.button.setLayoutParams(layoutParams);
}
});
ValueAnimator widthAnimation = ValueAnimator.ofInt(mParams.fromWidth, mParams.toWidth);
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int val = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mParams.button.getLayoutParams();
layoutParams.width = val;
mParams.button.setLayoutParams(layoutParams);
}
});
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(mParams.duration);
animatorSet.playTogether(strokeWidthAnimation, strokeColorAnimation, cornerAnimation, bgColorAnimation,
heightAnimation, widthAnimation);
animatorSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if (mParams.animationListener != null) {
mParams.animationListener.onAnimationEnd();
}
}
});
animatorSet.start();
}
}
public class StrokeGradientDrawable {
private int mStrokeWidth;
private int mStrokeColor;
private GradientDrawable mGradientDrawable;
private float mRadius;
private int mColor;
public StrokeGradientDrawable(GradientDrawable drawable) {
mGradientDrawable = drawable;
}
public int getStrokeWidth() {
return mStrokeWidth;
}
public void setStrokeWidth(int strokeWidth) {
mStrokeWidth = strokeWidth;
mGradientDrawable.setStroke(strokeWidth, getStrokeColor());
}
public int getStrokeColor() {
return mStrokeColor;
}
public void setStrokeColor(int strokeColor) {
mStrokeColor = strokeColor;
mGradientDrawable.setStroke(getStrokeWidth(), strokeColor);
}
public void setCornerRadius(float radius) {
mRadius = radius;
mGradientDrawable.setCornerRadius(radius);
}
public void setColor(int color) {
mColor = color;
mGradientDrawable.setColor(color);
}
public int getColor() {
return mColor;
}
public float getRadius() {
return mRadius;
}
public GradientDrawable getGradientDrawable() {
return mGradientDrawable;
}
}
}
Add this widget in your layout.xml
<com.test.widgets.MorphingButton
android:id="#+id/btnDone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DONE"/>
In Activity to animate view onButtonClick
write below code inside `MorphingButton` onClick
MorphingButton.Params circle = MorphingButton.Params.create()//To animate in circle from rect-round
.duration(500)
.cornerRadius((int) getResources().getDimension(R.dimen._100sdp))
.width((int) getResources().getDimension(R.dimen._56sdp))
.height((int) getResources().getDimension(R.dimen._56sdp))
.color(Color.BLUE) // normal state color
.colorPressed(Color.GREEN) // pressed state color
.icon(R.drawable.ic_loader); // icon
btnDone.morph(circle);
//To animate from circle to rect-round to this demo purpose
btnDone.postDelayed(new Runnable() {
#Override
public void run() {
MorphingButton.Params square = MorphingButton.Params.create()
.duration(500)
.cornerRadius((int) getResources().getDimension(R.dimen._100sdp))
.width((int) getResources().getDimension(R.dimen._100sdp))
.height((int) getResources().getDimension(R.dimen._56sdp))
.color(Color.BLUE) // normal state color
.colorPressed(Color.GREEN) // pressed state color
.icon(R.drawable.ic_loader) // icon
.text("DONE");
btnDone.morph(square);
}
}, 5000);

Set default menuItem for BottomNavigationView

How can i set the default MenuItem for the official BottomNavigationView (com.android.support:design:25.0.1)?
If I call programmatically menuItem.setCheckable(true).setChecked(true) the zoom effect is not performed and the BottomNavigationView shows like this:
There is more simpler way to do this since Android Support Library 25.3.0 :
bottomNavigationView.setSelectedItemId(R.id.id_of_item_you_want_to_select_as_default);
I achieved this in a much simpler way:
//R.id.bottom_bar_icon is the icon you would like clicked by default
bottomNavigationView.getMenu().performIdentifierAction(R.id.bottom_bar_icon, 0);
//set the corresponding menu item to checked = true
//and the other items to checked = false
bottomNavigationView.getMenu().getItem(0).setChecked(false);
bottomNavigationView.getMenu().getItem(1).setChecked(true);
bottomNavigationView.getMenu().getItem(2).setChecked(false);
In the end I was able to achieve this issue extending the BottomNavigationView like this:
public class RichBottomNavigationView extends BottomNavigationView {
private ViewGroup mBottomItemsHolder;
private int mLastSelection = INVALID_POSITION;
private Drawable mShadowDrawable;
private boolean mShadowVisible = true;
private int mWidth;
private int mHeight;
private int mShadowElevation = 2;
public RichBottomNavigationView(Context context) {
super(context);
init();
}
public RichBottomNavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RichBottomNavigationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
;
}
private void init() {
mShadowDrawable = ContextCompat.getDrawable(getContext(), R.drawable.shadow);
if (mShadowDrawable != null) {
mShadowDrawable.setCallback(this);
}
setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
setShadowVisible(true);
setWillNotDraw(false);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h + mShadowElevation, oldw, oldh);
mWidth = w;
mHeight = h;
updateShadowBounds();
}
private void updateShadowBounds() {
if (mShadowDrawable != null && mBottomItemsHolder != null) {
mShadowDrawable.setBounds(0, 0, mWidth, mShadowElevation);
}
ViewCompat.postInvalidateOnAnimation(this);
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mShadowDrawable != null && mShadowVisible) {
mShadowDrawable.draw(canvas);
}
}
public void setShadowVisible(boolean shadowVisible) {
setWillNotDraw(!mShadowVisible);
updateShadowBounds();
}
public int getShadowElevation() {
return mShadowVisible ? mShadowElevation : 0;
}
public int getSelectedItem() {
return mLastSelection = findSelectedItem();
}
#CallSuper
public void setSelectedItem(int position) {
if (position >= getMenu().size() || position < 0) return;
View menuItemView = getMenuItemView(position);
if (menuItemView == null) return;
MenuItemImpl itemData = ((MenuView.ItemView) menuItemView).getItemData();
itemData.setChecked(true);
boolean previousHapticFeedbackEnabled = menuItemView.isHapticFeedbackEnabled();
menuItemView.setSoundEffectsEnabled(false);
menuItemView.setHapticFeedbackEnabled(false); //avoid hearing click sounds, disable haptic and restore settings later of that view
menuItemView.performClick();
menuItemView.setHapticFeedbackEnabled(previousHapticFeedbackEnabled);
menuItemView.setSoundEffectsEnabled(true);
mLastSelection = position;
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
BottomNavigationState state = new BottomNavigationState(superState);
mLastSelection = getSelectedItem();
state.lastSelection = mLastSelection;
return state;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof BottomNavigationState)) {
super.onRestoreInstanceState(state);
return;
}
BottomNavigationState bottomNavigationState = (BottomNavigationState) state;
mLastSelection = bottomNavigationState.lastSelection;
dispatchRestoredState();
super.onRestoreInstanceState(bottomNavigationState.getSuperState());
}
private void dispatchRestoredState() {
if (mLastSelection != 0) { //Since the first item is always selected by the default implementation, dont waste time
setSelectedItem(mLastSelection);
}
}
private View getMenuItemView(int position) {
View bottomItem = mBottomItemsHolder.getChildAt(position);
if (bottomItem instanceof MenuView.ItemView) {
return bottomItem;
}
return null;
}
private int findSelectedItem() {
int itemCount = getMenu().size();
for (int i = 0; i < itemCount; i++) {
View bottomItem = mBottomItemsHolder.getChildAt(i);
if (bottomItem instanceof MenuView.ItemView) {
MenuItemImpl itemData = ((MenuView.ItemView) bottomItem).getItemData();
if (itemData.isChecked()) return i;
}
}
return INVALID_POSITION;
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
mBottomItemsHolder = (ViewGroup) getChildAt(0);
updateShadowBounds();
//This sucks.
MarginLayoutParams layoutParams = (MarginLayoutParams) mBottomItemsHolder.getLayoutParams();
layoutParams.topMargin = (mShadowElevation + 2) / 2;
}
static class BottomNavigationState extends BaseSavedState {
public int lastSelection;
#RequiresApi(api = Build.VERSION_CODES.N)
public BottomNavigationState(Parcel in, ClassLoader loader) {
super(in, loader);
lastSelection = in.readInt();
}
public BottomNavigationState(Parcelable superState) {
super(superState);
}
#Override
public void writeToParcel(#NonNull Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(lastSelection);
}
public static final Parcelable.Creator<NavigationView.SavedState> CREATOR
= ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<NavigationView.SavedState>() {
#Override
public NavigationView.SavedState createFromParcel(Parcel parcel, ClassLoader loader) {
return new NavigationView.SavedState(parcel, loader);
}
#Override
public NavigationView.SavedState[] newArray(int size) {
return new NavigationView.SavedState[size];
}
});
}
}
and calling setSelectedItem(2)

How to change pattern lock viewgroup drawable images dynamically?

Currently I'm developing a pattern lock application and in that application I extend pattern View from Viewgroup, it means it can display pattern lock View and I am using drawable png image to display pattern View.
So, actually I want to change that pattern lock png image dynamically when user selects that image in another GridView and display it on the pattern View.
Basically, I want to change only pattern lock theme.
Main screenshote of lockscreen
Here this is my pattern lock view xml
<com.v1.sensoft.halloweenlock.utils.Lock9View
android:id="#+id/lock_9_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:nodeSrc="#mipmap/ppo"
app:nodeOnSrc="#mipmap/ppn"
android:layout_gravity="center"
app:lineColor="#FFCC00"
app:lineWidth="8dp" />
In that xml app:nodeSrc="#mipmap/ppo" app:nodeOnSrc="#mipmap/ppn"is the image to display on pattern lock.
This is my pattern lock view
public class Lock9View extends ViewGroup {
private Paint paint;
private Bitmap bitmap;
private Canvas canvas;
private List<Pair<NodeView, NodeView>> lineList;
private NodeView currentNode;
private StringBuilder pwdSb;
private CallBack callBack;
private Drawable nodeSrc;
private Drawable nodeOnSrc;
public Lock9View(Context context) {
this(context, null);
}
public Lock9View(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Lock9View(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public Lock9View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr); // TODO api 21
initFromAttributes(attrs, defStyleAttr);
}
private void initFromAttributes(AttributeSet attrs, int defStyleAttr) {
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Lock9View, defStyleAttr, 0);
nodeSrc = a.getDrawable(R.styleable.Lock9View_nodeSrc);
nodeOnSrc = a.getDrawable(R.styleable.Lock9View_nodeOnSrc);
int lineColor = Color.argb(0, 0, 0, 0);
lineColor = a.getColor(R.styleable.Lock9View_lineColor, lineColor);
float lineWidth = 20.0f;
lineWidth = a.getDimension(R.styleable.Lock9View_lineWidth, lineWidth);
a.recycle();
paint = new Paint(Paint.DITHER_FLAG);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(lineWidth);
paint.setColor(lineColor);
paint.setAntiAlias(true);
DisplayMetrics dm = getResources().getDisplayMetrics();
bitmap = Bitmap.createBitmap(dm.widthPixels, dm.widthPixels, Bitmap.Config.ARGB_8888);
canvas = new Canvas();
canvas.setBitmap(bitmap);
for (int n = 0; n < 9; n++) {
NodeView node = new NodeView(getContext(), n + 1);
addView(node);
}
lineList = new ArrayList<Pair<NodeView,NodeView>>();
pwdSb = new StringBuilder();
setWillNotDraw(false);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (!changed) {
return;
}
int width = right - left;
int nodeWidth = width / 3;
int nodePadding = nodeWidth / 6;
for (int n = 0; n < 9; n++) {
NodeView node = (NodeView) getChildAt(n);
int row = n / 3;
int col = n % 3;
int l = col * nodeWidth + nodePadding;
int t = row * nodeWidth + nodePadding;
int r = col * nodeWidth + nodeWidth - nodePadding;
int b = row * nodeWidth + nodeWidth - nodePadding;
node.layout(l, t, r, b);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
NodeView nodeAt = getNodeAt(event.getX(), event.getY());
if (nodeAt == null && currentNode == null) {
return true;
} else {
clearScreenAndDrawList();
if (currentNode == null) {
currentNode = nodeAt;
currentNode.setHighLighted(true);
pwdSb.append(currentNode.getNum());
}
else if (nodeAt == null || nodeAt.isHighLighted()) {
canvas.drawLine(currentNode.getCenterX(), currentNode.getCenterY(), event.getX(), event.getY(), paint);
} else {
canvas.drawLine(currentNode.getCenterX(), currentNode.getCenterY(), nodeAt.getCenterX(), nodeAt.getCenterY(), paint);
nodeAt.setHighLighted(true);
Pair<NodeView, NodeView> pair = new Pair<NodeView, NodeView>(currentNode, nodeAt);
lineList.add(pair);
currentNode = nodeAt;
pwdSb.append(currentNode.getNum());
}
invalidate();
}
return true;
case MotionEvent.ACTION_UP:
if (pwdSb.length() <= 0) {
return super.onTouchEvent(event);
}
if (callBack != null) {
callBack.onFinish(pwdSb.toString());
pwdSb.setLength(0);
}
currentNode = null;
lineList.clear();
clearScreenAndDrawList();
for (int n = 0; n < getChildCount(); n++) {
NodeView node = (NodeView) getChildAt(n);
node.setHighLighted(false);
}
invalidate();
return true;
}
return super.onTouchEvent(event);
}
private void clearScreenAndDrawList() {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
for (Pair<NodeView, NodeView> pair : lineList) {
canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(), pair.second.getCenterX(), pair.second.getCenterY(), paint);
}
}
private NodeView getNodeAt(float x, float y) {
for (int n = 0; n < getChildCount(); n++) {
NodeView node = (NodeView) getChildAt(n);
if (!(x >= node.getLeft() && x < node.getRight())) {
continue;
}
if (!(y >= node.getTop() && y < node.getBottom())) {
continue;
}
return node;
}
return null;
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
public class NodeView extends View {
private int num;
private boolean highLighted;
private NodeView(Context context) {
super(context);
}
public NodeView(Context context, int num) {
this(context);
this.num = num;
highLighted = false;
if (nodeSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeSrc);
}
}
public boolean isHighLighted() {
return highLighted;
}
public void setHighLighted(boolean highLighted) {
this.highLighted = highLighted;
if (highLighted) {
if (nodeOnSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeOnSrc);
}
} else {
if (nodeSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeSrc);
}
}
}
public int getCenterX() {
return (getLeft() + getRight()) / 2;
}
public int getCenterY() {
return (getTop() + getBottom()) / 2;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public interface CallBack {
public void onFinish(String password);
}
Activity
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
lock9View = (Lock9View) findViewById(R.id.lock_9_view);
lock9View.setCallBack(new Lock9View.CallBack() {
public int counter = 0;
public int buttCounter = 0;
#Override
public void onFinish(String password) {
PATTERN_KEY = prefs.getString("Pattern", "invalid");
Log.i("Counter","..."+counter);
if (PATTERN_KEY.equals("invalid")) {
Toast.makeText(MainActivity.this, "Options --> Create new Pattern", Toast.LENGTH_LONG).show();
} else {
if (password.equals(PATTERN_KEY)) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
} else {
invalidPattern();
Toast.makeText(MainActivity.this, "Please try again..." +failedCount, Toast.LENGTH_LONG).show();
}
}
}
});
}
So,if anyone know please give some idea of that.

Calling onDraw() method of a custom View in Android

I have created a CustomView for Calendar. I have an onDraw method to draw the text in the calendar. I want to change the color of the day Text when i click on it. How can i achieve it?
CalendarView.java :
package com.example.calendar_module;
import java.util.Calendar;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.MonthDisplayHelper;
import android.view.MotionEvent;
import android.widget.ImageView;
public class CalendarView extends ImageView {
private static int WEEK_TOP_MARGIN = 0;
private static int WEEK_LEFT_MARGIN = 05;
private static int CELL_WIDTH = 20;
private static int CELL_HEIGH = 20;
private static int CELL_MARGIN_TOP = 05;
private static int CELL_MARGIN_LEFT = 29;
private static float CELL_TEXT_SIZE;
private static int CALENDAR_WIDTH;
private static int CALENDAR_HEIGHT;
private static final String TAG = "CalendarView";
private String[] mDayString = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
private Calendar mRightNow = null;
private Drawable mWeekTitle = null;
private Cell mToday = null;
private Cell[][] mCells = new Cell[6][7];
private Cell[] mDayCells = new Cell[7];
private OnCellTouchListener mOnCellTouchListener = null;
MonthDisplayHelper mHelper;
Drawable mDecoration = null;
public interface OnCellTouchListener {
public void onTouch(Cell cell);
}
public CalendarView(Context context) {
this(context, null);
}
public CalendarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CalendarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDecoration = context.getResources().getDrawable(R.drawable.typeb_calendar_today);
initCalendarView();
}
private void initCalendarView() {
mRightNow = Calendar.getInstance();
// prepare static vars
Resources res = getResources();
WEEK_TOP_MARGIN = (int) res.getDimension(R.dimen.week_top_margin);
WEEK_LEFT_MARGIN = (int) res.getDimension(R.dimen.week_left_margin);
CELL_WIDTH = (int) res.getDimension(R.dimen.cell_width);
CELL_HEIGH = (int) res.getDimension(R.dimen.cell_heigh);
CELL_MARGIN_TOP = (int) res.getDimension(R.dimen.cell_margin_top);
CELL_MARGIN_LEFT = (int) res.getDimension(R.dimen.cell_margin_left);
// CALENDAR_HEIGHT = 700;
// CALENDAR_WIDTH = 700;
//
CALENDAR_HEIGHT = (int) res.getDimension(R.dimen.calendar_height);
CALENDAR_WIDTH = (int) res.getDimension(R.dimen.calendar_width);
System.out.println("Width and Hight :"+CALENDAR_WIDTH+" "+CALENDAR_HEIGHT);
System.out.println("Dimen Width and Height : "+R.dimen.calendar_width+" "+R.dimen.calendar_height);
CELL_TEXT_SIZE = res.getDimension(R.dimen.cell_text_size);
// set background
// setImageResource(R.drawable.background);
mWeekTitle = res.getDrawable(R.drawable.calendar_week);
mHelper = new MonthDisplayHelper(mRightNow.get(Calendar.YEAR), mRightNow.get(Calendar.MONTH));
}
private void initCells() {
class _calendar {
public int day;
public boolean thisMonth;
public _calendar(int d, boolean b) {
day = d;
thisMonth = b;
}
public _calendar(int d) {
this(d, false);
}
};
_calendar tmp[][] = new _calendar[6][7];
for(int i=0; i<tmp.length; i++) {
int n[] = mHelper.getDigitsForRow(i);
for(int d=0; d<n.length; d++) {
if(mHelper.isWithinCurrentMonth(i,d))
tmp[i][d] = new _calendar(n[d], true);
else
tmp[i][d] = new _calendar(n[d]);
}
}
Calendar today = Calendar.getInstance();
int thisDay = 0;
mToday = null;
if(mHelper.getYear()==today.get(Calendar.YEAR) && mHelper.getMonth()==today.get(Calendar.MONTH)) {
thisDay = today.get(Calendar.DAY_OF_MONTH);
}
// build cells
Rect Bound = new Rect(CELL_MARGIN_LEFT, CELL_MARGIN_TOP, CELL_WIDTH+CELL_MARGIN_LEFT, CELL_HEIGH+CELL_MARGIN_TOP);
// for( int i=0 ; i < 7 ; i++ )
// {
//
// mDayCells[i] = new Cell(mDayString[i],new Rect(Bound),CELL_TEXT_SIZE);
// Bound.offset(CELL_WIDTH, 0);
//
// }
//
// Bound.offset(0, CELL_HEIGH); // move to next row and first column
// Bound.left = CELL_MARGIN_LEFT;
// Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
//
for(int week=0; week<mCells.length; week++) {
for(int day=0; day<mCells[week].length; day++)
{
if(tmp[week][day].thisMonth) {
if(day==0 || day==6 )
mCells[week][day] = new RedCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
else
mCells[week][day] = new Cell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
} else {
mCells[week][day] = new GrayCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
}
Bound.offset(CELL_WIDTH, 0); // move to next column
// get today
if(tmp[week][day].day==thisDay && tmp[week][day].thisMonth) {
mToday = mCells[week][day];
mDecoration.setBounds(mToday.getBound());
}
}
Bound.offset(0, CELL_HEIGH); // move to next row and first column
Bound.left = CELL_MARGIN_LEFT;
Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
}
}
#Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
// Rect re = getDrawable().getBounds();
// WEEK_LEFT_MARGIN = CELL_MARGIN_LEFT = (right-left - re.width()) / 2;
// mWeekTitle.setBounds(WEEK_LEFT_MARGIN, WEEK_TOP_MARGIN, WEEK_LEFT_MARGIN+mWeekTitle.getMinimumWidth(), WEEK_TOP_MARGIN+mWeekTitle.getMinimumHeight());
initCells();
super.onLayout(changed, left, top, right, bottom);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
System.out.println("Width : "+CALENDAR_WIDTH);
System.out.println("Height : "+CALENDAR_HEIGHT);
setMeasuredDimension(CALENDAR_WIDTH, CALENDAR_HEIGHT);
// setMeasuredDimension(100,200);
}
public void setTimeInMillis(long milliseconds) {
mRightNow.setTimeInMillis(milliseconds);
initCells();
this.invalidate();
}
public int getYear() {
return mHelper.getYear();
}
public int getMonth() {
return mHelper.getMonth();
}
public void nextMonth() {
mHelper.nextMonth();
initCells();
invalidate();
}
public void previousMonth() {
mHelper.previousMonth();
initCells();
invalidate();
}
public boolean firstDay(int day) {
return day==1;
}
public boolean lastDay(int day) {
return mHelper.getNumberOfDaysInMonth()==day;
}
public void goToday() {
Calendar cal = Calendar.getInstance();
mHelper = new MonthDisplayHelper(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH));
initCells();
invalidate();
}
public Calendar getDate() {
return mRightNow;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(mOnCellTouchListener!=null){
for(Cell[] week : mCells) {
for(Cell day : week) {
if(day.hitTest((int)event.getX(), (int)event.getY())) {
mOnCellTouchListener.onTouch(day);
}
}
}
}
return super.onTouchEvent(event);
}
public void setOnCellTouchListener(OnCellTouchListener p) {
mOnCellTouchListener = p;
}
#Override
protected void onDraw(Canvas canvas) {
// draw background
super.onDraw(canvas);
mWeekTitle.draw(canvas);
// draw cells
for(Cell[] week : mCells) {
for(Cell day : week) {
day.draw(canvas);
}
}
// draw today
if(mDecoration!=null && mToday!=null) {
mDecoration.draw(canvas);
}
}
public class GrayCell extends Cell {
public GrayCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(Color.LTGRAY);
}
}
private class RedCell extends Cell {
public RedCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(0xdddd0000);
}
}
}
Cell.java :
package com.example.calendar_module;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Cell {
private static final String TAG = "Cell";
protected Rect mBound = null;
protected int mDayOfMonth = 1; // from 1 to 31
protected Paint mPaint = new Paint(Paint.SUBPIXEL_TEXT_FLAG
|Paint.ANTI_ALIAS_FLAG);
int dx, dy;
protected String mDayString;
private Cell cell ;
public Cell(int dayOfMon, Rect rect, float textSize, boolean bold) {
mDayOfMonth = dayOfMon;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayOfMonth)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(String day,Rect rect,float textSize,boolean bold)
{
mDayString = day;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayString)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(String day , Rect rect , float textSize , int newColor)
{
mDayString = day;
mBound = rect;
mPaint.setTextSize(textSize);
mPaint.setColor(newColor);
dx = (int) mPaint.measureText(String.valueOf(mDayString)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(int dayOfMon, Rect rect, float textSize) {
this(dayOfMon, rect, textSize, false);
}
public Cell(String day,Rect rect,float textSize)
{
this(day,rect,textSize,false);
}
protected void draw(Canvas canvas) {
canvas.drawText(String.valueOf(mDayOfMonth), mBound.centerX() - dx, mBound.centerY() + dy, mPaint);
}
public int getDayOfMonth() {
return mDayOfMonth;
}
public boolean hitTest(int x, int y) {
return mBound.contains(x, y);
}
public Rect getBound() {
return mBound;
}
public String toString() {
return String.valueOf(mDayOfMonth)+"("+mBound.toString()+")";
}
}
CalendarActivity.java
package com.example.calendar_module;
import java.util.GregorianCalendar;
import com.example.calendar_module.CalendarView.OnCellTouchListener;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CalendarActivity extends Activity{
public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.example.calendar_module.date";
public static String mClickedDate, mClickedMonth;
CalendarView mView = null;
TextView mHit;
Handler mHandler = new Handler();
private Button mNextButton;
private Button mPreviousButton;
private TextView mMonthText ;
private int mMonthInt;
private ListView mEventListView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mView = (CalendarView)findViewById(R.id.calendar);
mEventListView = (ListView) findViewById(R.id.EventsList);
mEventListView.setAdapter(new BadgeAdapter(this));
mView.setOnCellTouchListener(new OnCellTouchListener() {
#Override
public void onTouch(Cell cell) {
TextView mMonthText = (TextView)findViewById(R.id.MonthText);
mClickedDate = ""+cell.getDayOfMonth();
mClickedMonth =""+mMonthText.getText();
// System.out.println("Clicked date is : "+mClickedDate+" "+mClickedMonth);
// startActivity(new Intent(CalendarActivity.this,Event.class));
// cell = new Cell(cell.getDayOfMonth(),new Rect(cell.getBound()),Color.MAGENTA);
}
});
mNextButton = (Button) findViewById(R.id.NextMonth);
mPreviousButton = (Button) findViewById(R.id.PreviousMonth);
mMonthText = (TextView) findViewById(R.id.MonthText);
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
// System.out.println("CurrentMonth is : "+mView.getMonth());
// if(getIntent().getAction().equals(Intent.ACTION_PICK))
// findViewById(R.id.hint).setVisibility(View.INVISIBLE);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mView.nextMonth();
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
}
});
mPreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mView.previousMonth();
mMonthText.setText(DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG)+", "+mView.getYear());
}
});
System.out.println("Calendar View Height : "+mView.getHeight());
}
private class RedCell extends Cell {
public RedCell(Cell cell) {
super(cell.getDayOfMonth(),new Rect(cell.getBound()), R.dimen.cell_text_size);
mPaint.setColor(Color.RED);
}
}
}
Call mView.invalidate(); in your onClick() method for that View. This will call onDraw() (eventually), which will then run the drawing code for your view.

Categories

Resources