Hide buttons on start of Android app - android

I have a MenuView ViewGroup which capsules all the buttons of my interface.
On start of the app all buttons are positioned via button.layout(). Then I hide all buttons, with one exception: the menu button. When I am pressing the menu button, all other buttons are shown (via a zoom animation).
Now the problem: while positioning the buttons via button.layout(), they are visible. So almost 1 sec all buttons are shown on startup of the app.
How can I avoid that?
My button code:
public class CircleButton extends Button {
static final int StateDefault = 0;
static final int StateFocused = 1;
static final int StatePressed = 2;
private Bitmap mBitmapDefault;
private String mCaption;
protected int radius;
protected int color = 0xff000000;
private Typeface font1;
private boolean visible = true;
private int savedLeft, savedTop;
// indicates whether the button is visible when the menu is rendered
public boolean visibleInMenu = true;
private Paint paint;
private static String TAG = "CircleButton";
public int getRadius(){
return radius;
}
public CircleButton setRadius(int radius){
this.radius = radius;
this.setWidth(2*radius);
this.setHeight(2*radius);
return this;
}
public CircleButton setColor(int color){
this.color = color;
return this;
}
public CircleButton setCaption(String caption){
mCaption = caption;
return this;
}
public CircleButton(Context context) {
super(context);
init(context);
}
public CircleButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CircleButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
setClickable(true);
setBackgroundColor(0x00000000);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
font1 = Typeface.createFromAsset(context.getAssets(), "fonts/Bebas/BEBAS___.ttf");
mCaption = "Caption";
this.setRadius(45);
this.setTextSize(18);
setOnClickListener(onClickListener);
setOnTouchListener(onTouchListener);
}
public void setVisibility(int visibility) {
if(visibility == GONE){
this.visible = false;
}else{
this.visible = true;
}
super.setVisibility(visibility);
}
/**
* draws the normal button (without rollover)
* #param canvas
*/
protected void drawDefault(Canvas canvas){
//canvas.drawARGB(255, 255, 0, 0);
Paint paintText = new Paint();
paintText.setAntiAlias(true);
paintText.setTextSize(this.getTextSize());
paintText.setColor(0xffffffff); // white
paintText.setTypeface(this.font1);
Rect bounds = new Rect();
//Paint textPaint = this.getPaint();
paintText.getTextBounds(mCaption,0,mCaption.length(),bounds);
float left = (float) (2*radius-bounds.width())/2;
float top = (float) radius+bounds.height()/2;
//Log.v("Button","bounds:"+bounds.width()+"x"+bounds.height());
//Log.v("Button","this.getWIdth:"+2*radius);
// create the Drawing Tool (Brush)
Paint paint = new Paint();
paint.setAntiAlias(true); // for a nicer paint
paint.setColor(color);
paint.setStrokeWidth(1);
paint.setStyle(Style.FILL);
Path path = new Path();
path.addCircle(radius, radius, radius, Path.Direction.CW);
canvas.drawPath(path, paint);
canvas.save();
canvas.rotate(-45,this.getRadius(),this.getRadius());
canvas.drawText(mCaption, left, top, paintText);
canvas.restore();
}
protected Bitmap getDefaultBitmap(){
if(mBitmapDefault == null){
mBitmapDefault = Bitmap.createBitmap(2*radius, 2*radius, Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmapDefault);
this.drawDefault(canvas);
return mBitmapDefault;
}
return mBitmapDefault;
}
#Override
protected void onDraw(Canvas canvas) {
//Log.v("Button","onDraw(): "+this.getWidth()+"x"+this.getHeight());
super.onDraw(canvas);
canvas.drawBitmap(this.getDefaultBitmap(), 0, 0, paint);
//super.onDraw(canvas);
//canvas.drawBitmap(this.getDefaultBitmap(), new Rect(0, 0, this.radius*8, this.radius*8), new Rect(0,0, this.radius*2, this.radius*2), null);
}
public void recycle() {
if(mBitmapDefault != null){
mBitmapDefault.recycle();
mBitmapDefault = null;
}
}
public void hide(){
this.hide(true);
}
public void hide(boolean withAnimation){
if(this.visible == true){
savedLeft = getLeft();
savedTop = getTop();
ScaleAnimation anim = new ScaleAnimation(1, 0, 1, 0, this.getRadius(), this.getRadius());
anim.setDuration(300);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
visible = false;
layout(0, 0, 0, 0);
}
});
this.startAnimation(anim);
}
}
public void show(){
if(this.visible == false){
this.setVisibility(VISIBLE);
OvershootInterpolator inter = new OvershootInterpolator();
ScaleAnimation anim = new ScaleAnimation(0, 1, 0, 1, this.getRadius(), this.getRadius());
anim.setDuration(300);
anim.setInterpolator(inter);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) { }
#Override
public void onAnimationRepeat(Animation animation) { }
#Override
public void onAnimationEnd(Animation animation) {
visible = true;
}
});
this.startAnimation(anim);
this.layout(this.savedLeft, this.savedTop, this.savedLeft+2*this.radius, this.savedTop+2*this.radius);
}
this.visible = true;
}
public CircleButton setOnClickCallback(OnClickListener l) {
super.setOnClickListener(l);
return this;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
}
};
private OnTouchListener onTouchListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//Log.v("Button","onTouch()");
if(event.getAction() == MotionEvent.ACTION_DOWN){
OvershootInterpolator inter = new OvershootInterpolator();
ScaleAnimation anim = new ScaleAnimation(1, (float) 1.5, 1,(float) 1.5, CircleButton.this.getRadius(), CircleButton.this.getRadius());
anim.setInterpolator(inter);
anim.setDuration(200);
anim.setFillAfter(true);
CircleButton.this.startAnimation(anim);
}else if(event.getAction() == MotionEvent.ACTION_UP){
ScaleAnimation anim = new ScaleAnimation((float) 1.5, 1, (float) 1.5, 1, CircleButton.this.getRadius(), CircleButton.this.getRadius());
anim.setDuration(300);
anim.setFillAfter(true);
CircleButton.this.startAnimation(anim);
}
return false;
}
};
}

Use setVisibility(int visibility) method on the object to hide it with Parameter visibility One of VISIBLE, INVISIBLE, or GONE:
GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.
Constant Value: 8 (0x00000008)
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.
Constant Value: 4 (0x00000004)
VISIBLE
This view is visible. Use with setVisibility(int) and android:visibility.
Constant Value: 0 (0x00000000)

Try putting android:visibility="invisible" to those buttons in your layout xml.

Related

fade in out dots in custom dotted progress view

i have created a custom dotted progress view with 3 dots inspired by #Naveen Shriyan answer in this question How to make custom dotted progress bar in android?
public class DottedProgressView extends View {
//actual dot radius
private int mDotRadius = 25;
private Paint paint = new Paint();
//Bounced Dot Radius
private int mBounceDotRadius = 25;
//to get identified in which position dot has to bounce
private int mDotPosition;
//specify how many dots you need in a progressbar
private int mDotAmount = 3;
public DottedProgressView(Context context) {
super(context);
}
public DottedProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DottedProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//function to create dot
createDot(canvas,paint);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width;
int height;
//calculate the view width
int calculatedWidth = (75*3);
width = calculatedWidth;
height = (mDotRadius*2+10);
//MUST CALL THIS
setMeasuredDimension(width, height);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
startAnimation();
}
private void createDot(Canvas canvas, Paint paint) {
//here i have setted progress bar with 10 dots , so repeat and wnen i = mDotPosition then increase the radius of dot i.e mBounceDotRadius
for(int i = 0; i < mDotAmount; i++ ){
if(i == mDotPosition){
paint.setColor(Color.parseColor("#FB8C00"));
canvas.drawCircle(30+(i*75), mDotRadius, mDotRadius, paint);
} else if (i == mDotPosition - 1) {
paint.setColor(Color.parseColor("#FFA726"));
canvas.drawCircle(30+(i*75), mDotRadius, mDotRadius, paint);
}
else {
paint.setColor(Color.parseColor("#FFE0B2"));
canvas.drawCircle(30+(i*75), mDotRadius, mDotRadius, paint);
}
}
}
private void startAnimation() {
BounceAnimation bounceAnimation = new BounceAnimation();
bounceAnimation.setDuration(180);
bounceAnimation.scaleCurrentDuration(1.5f);
bounceAnimation.setRepeatCount(Animation.INFINITE);
bounceAnimation.setInterpolator(new FastOutSlowInInterpolator());
bounceAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {
mDotPosition++;
//when mDotPosition == mDotAmount , then start again applying animation from 0th positon , i.e mDotPosition = 0;
if (mDotPosition == mDotAmount) {
mDotPosition = 0;
}
}
});
startAnimation(bounceAnimation);
}
private class BounceAnimation extends Animation {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
//call invalidate to redraw your view againg.
invalidate();
}
}
}
I would like also to add a fade in out animation to each dot as the animation occurs to make the transition between the 3 dots smoother. How can i achieve this?

Canvas is not drawing in custom Android View

I have created my custom View in Android and trying to draw a circle in that but nothing is drawing but with no errors.
Here is my code
public class ColorOptionsView extends RelativeLayout {
private View mValue;
private ImageView mImage;
private Paint paint;
String cirlceText;
int circleColor,circleTextColor;
float circleTextSize;
public ColorOptionsView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorOptionsView, 0, 0);
try {
cirlceText = a.getString(R.styleable.ColorOptionsView_circleText);
circleColor = a.getColor(R.styleable.ColorOptionsView_circleColor, 0);
circleTextColor = a.getColor(R.styleable.ColorOptionsView_circleTextColor, 0);
circleTextSize = a.getFloat(R.styleable.ColorOptionsView_circleTextSize,20);
} finally {
a.recycle();
}
}
public void setCirlceText(String cirlceText) {
this.cirlceText = cirlceText;
invalidate();
requestLayout();
}
public void setCircleColor(int circleColor) {
this.circleColor = circleColor;
invalidate();
requestLayout();
}
public void setCircleTextColor(int circleTextColor) {
this.circleTextColor = circleTextColor;
invalidate();
requestLayout();
}
public void setCircleTextSize(float circleTextSize) {
this.circleTextSize = circleTextSize;
invalidate();
requestLayout();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(circleColor);
int centerX = this.getMeasuredWidth()/2;
int centerY = this.getMeasuredHeight()/2;
int raduis = 150;
canvas.drawCircle(centerX,centerY,raduis,paint);
paint.setColor(circleTextColor);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(cirlceText,centerX,centerY,paint);
canvas.drawLine(0,100,100,0,paint);
}
I am not getting where I went wrong. Devs check it and help me out.

Custom instruction overlay with highlighted view (without using ShowcaseViewLibrary)

I would like to know if there is any simple solution to creating an overlay where an element would get highlighted.
So the final result would look something like this:
I would like to avoid using ShowcaseViewLibrary from variety of reason (it doesn't have the look I need, it's no longer supported etc.).
I thought about using FrameLayout but I am not sure how to achieve the highlighted existing element. Also putting the arrows or bubbles to the elements so they connect precisely.
A quick and easy way would be to make a copy of the Activity you want to demonstrate with overlays added and just show that. It's what I do and it works fine.
/**
* Created by Nikola D. on 10/1/2015.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ShowCaseLayout extends ScrimInsetsFrameLayout {
private static final long DEFAULT_DURATION = 1000;
private static final int DEFAULT_RADIUS = 100;
private Paint mEmptyPaint;
private AbstractQueue<Pair<String, View>> mTargetQueue;
private int mLastCenterX = 600;
private int mLastCenterY = 100;
private ValueAnimator.AnimatorUpdateListener mAnimatorListenerX = new ValueAnimator.AnimatorUpdateListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onAnimationUpdate(ValueAnimator animation) {
mLastCenterX = (int) animation.getAnimatedValue();
setWillNotDraw(false);
postInvalidate();
}
};
private ValueAnimator.AnimatorUpdateListener mAnimatorListenerY = new ValueAnimator.AnimatorUpdateListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onAnimationUpdate(ValueAnimator animation) {
mLastCenterY = (int) animation.getAnimatedValue();
setWillNotDraw(false);
postInvalidate();
}
};
private ValueAnimator mCenterAnimatorX;
private ValueAnimator mCenterAnimatorY;
private boolean canRender = false;
private OnAttachStateChangeListener mAttachListener = new OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
canRender = true;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
public void onViewDetachedFromWindow(View v) {
canRender = false;
removeOnAttachStateChangeListener(this);
}
};
private long mDuration = DEFAULT_DURATION;
private int mRadius = (int) DEFAULT_RADIUS;
private Interpolator mInterpolator = new LinearOutSlowInInterpolator();
private ValueAnimator mRadiusAnimator;
private ValueAnimator.AnimatorUpdateListener mRadiusAnimatorListener = new ValueAnimator.AnimatorUpdateListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onAnimationUpdate(ValueAnimator animation) {
mRadius = (int) animation.getAnimatedValue();
}
};
private TextView mDescriptionText;
private Button mGotItButton;
private OnClickListener mExternalGotItButtonlistener;
private OnClickListener mGotItButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
setNextTarget();
if (mExternalGotItButtonlistener != null) {
mExternalGotItButtonlistener.onClick(v);
}
}
};
private Animator.AnimatorListener mAnimatorSetListener = new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
setNextTarget();
invalidate();
//mDescriptionText.layout(mTempRect.left, mTempRect.bottom + mTempRect.bottom, mDescriptionText. );
}
};
private Rect mTempRect;
private Paint mBackgroundPaint;
private Bitmap bitmap;
private Canvas temp;
private int mStatusBarHeight = 0;
public ShowCaseLayout(Context context) {
super(context);
setupLayout();
}
public ShowCaseLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setupLayout();
}
public ShowCaseLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupLayout();
}
public void setTarget(View target, String hint) {
mTargetQueue.add(new Pair<>(hint, target));
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setupLayout() {
mTargetQueue = new LinkedBlockingQueue<>();
setWillNotDraw(false);
mBackgroundPaint = new Paint();
int c = Color.argb(127, Color.red(Color.RED), Color.blue(Color.RED), Color.green(Color.RED));
mBackgroundPaint.setColor(c);
mEmptyPaint = new Paint();
mEmptyPaint.setColor(Color.TRANSPARENT);
mEmptyPaint.setStyle(Paint.Style.FILL);
mEmptyPaint.setAntiAlias(true);
mEmptyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
if (!ViewCompat.isLaidOut(this))
addOnAttachStateChangeListener(mAttachListener);
else canRender = true;
mDescriptionText = new TextView(getContext());
mGotItButton = new Button(getContext());
mGotItButton.setText("GOT IT");
mGotItButton.setOnClickListener(mGotItButtonClickListener);
addView(mGotItButton, generateDefaultLayoutParams());
//ViewCompat.setAlpha(this, 0.5f);
}
#Override
protected LayoutParams generateDefaultLayoutParams() {
return new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!canRender) return;
temp.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mBackgroundPaint);
temp.drawCircle(mLastCenterX, mLastCenterY, mRadius, mEmptyPaint);
canvas.drawBitmap(bitmap, 0, 0, null);
}
#TargetApi(Build.VERSION_CODES.M)
private void animateCenterToNextTarget(View target) {
int[] locations = new int[2];
target.getLocationInWindow(locations);
int x = locations[0];
int y = locations[1];
mTempRect = new Rect(x, y, x + target.getWidth(), y + target.getHeight());
int centerX = mTempRect.centerX();
int centerY = mTempRect.centerY();
int targetRadius = Math.abs(mTempRect.right - mTempRect.left) / 2;
targetRadius += targetRadius * 0.05;
mCenterAnimatorX = ValueAnimator.ofInt(mLastCenterX, centerX).setDuration(mDuration);
mCenterAnimatorX.addUpdateListener(mAnimatorListenerX);
mCenterAnimatorY = ValueAnimator.ofInt(mLastCenterY, centerY).setDuration(mDuration);
mCenterAnimatorY.addUpdateListener(mAnimatorListenerY);
mRadiusAnimator = ValueAnimator.ofInt(mRadius, targetRadius);
mRadiusAnimator.addUpdateListener(mRadiusAnimatorListener);
playTogether(mCenterAnimatorY, mCenterAnimatorX, mRadiusAnimator);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
bitmap.eraseColor(Color.TRANSPARENT);
temp = new Canvas(bitmap);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void playTogether(ValueAnimator... animators) {
AnimatorSet set = new AnimatorSet();
set.setInterpolator(mInterpolator);
set.setDuration(mDuration);
set.playTogether(animators);
set.addListener(mAnimatorSetListener);
set.start();
}
public void start(Activity activity) {
if (getParent() == null) {
attachLayoutToWindow(activity);
}
setNextTarget();
}
private void setNextTarget() {
Pair<String, View> pair = mTargetQueue.poll();
if (pair != null) {
if (pair.second != null)
animateCenterToNextTarget(pair.second);
mDescriptionText.setText(pair.first);
}
}
private void attachLayoutToWindow(Activity activity) {
FrameLayout rootLayout = (FrameLayout) activity.findViewById(android.R.id.content);
rootLayout.addView(this);
}
public void hideShowcaseLayout() {
}
public void setGotItButtonClickistener(OnClickListener mExternalGotItButtonlistener) {
this.mExternalGotItButtonlistener = mExternalGotItButtonlistener;
}
public TextView getDescriptionTextView() {
return mDescriptionText;
}
public void setDescriptionTextView(TextView textView) {
mDescriptionText = textView;
}
}
Please note that this code is incomplete and is under development, you should tweak it according your needs.
This layout will draw a circle around the View over its Rect.
Instead of drawing the circle you could drawRect to the Rect bounds of the target view or drawRoundRect if the View's Rect and background drawable Rect are complementary.
Drawing the line (drawLine()) should be from the target view:
startX = (rect.right - rect.left)/2;
startY = rect.bottom;
endX = startX;
endY = startY + arbitraryLineHeight;
if the endY is larger than the layout height you should be drawing it upwards rect.top - arbitraryLineHeight, otherwise you draw it as it is.
arbitraryLineHeight could be descriptionViewRect.top which makes it more dynamic, instead of using a constant value.

Change the color of line draw line android

I'm using this app to draw free lines in android
DrawerView.java
public class DrawerView extends View {
public static Paint paint;
Paint paint2 = new Paint();
public Path path = new Path();
public Path circlePath = new Path();
public static int lineCol = Color.BLUE;
public static boolean isTouchable = false;
public LayoutParams params;
public DrawerView(Context context, AttributeSet attrs){
super(context, attrs);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(lineCol);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(4f);
}
public void onButtonPress(){
// resets the screen
path.reset();
// Calls the onDraw() method
postInvalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (!isTouchable){
return false;
} else {
// Gives you x and y coordinates on the Event.
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
circlePath.reset();
circlePath.addCircle(pointX, pointY, 30, Path.Direction.CW);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
postInvalidate();
return true;
}
}
}
DrawLines.java
public class DrawLines extends Activity {
DrawerView myView;
public Button btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.draw_line);
myView = (DrawerView)findViewById(R.id.custView);
btnReset = (Button) findViewById(R.id.button1);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// resets the screen
myView.path.reset();
// Calls the onDraw() method
myView.postInvalidate();
}
});
}
}
draw_line.xml
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear" />
<com.example.drawline.DrawerView
android:id="#+id/custView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_margin="5dp"
custom:lineColor="#ff0099" />
It works well with me but I want to be able to select the color of line, so I added a button in draw_line.xml that when press it show a dialog that asks the user to select color. this is the code of dialog
public void openSelectColorDialog()
{
final Dialog d = new Dialog(this);
d.setTitle("Select Color");
d.setContentView(R.layout.military_list);
int image[] = { R.drawable.black, R.drawable.blue, R.drawable.yellow};
ArrayList<HashMap<String, String>> objArayList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < image.length; i++) {
HashMap<String, String> listData = new HashMap<String, String>();
listData.put("image", Integer.toString(image[i]));
objArayList.add(listData);
}
String[] from = { "image"};
int[] to = { R.id.list_image };
SimpleAdapter listAdapter = new SimpleAdapter(this, objArayList,
R.layout.military_list_item, from, to);
ListView lst1 = (ListView) d.findViewById(android.R.id.list);
lst1.setAdapter(listAdapter);
lst1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
if (position == 0) {
// the code of color line
d.dismiss();
} else if (position == 1) {
// the code of blue line
d.dismiss();
} else {
// the code of yellow line
d.dismiss();
}
myView.postInvalidate();
}
});
d.show();
}
What is the code I have to add to make the color like what I selected ?
consider if I write this code
DrawerView.paint.setColor(Color.BLACK);
the whole line changes its color to the selected color and this is not what I want.
I want that the color of the new line is like what I selected and keep the old lines with its colors.
Hope anyone got my mean.
Thanks in advance.
Edit
the new code is:
ColoredPath.java
public class ColoredPath {
private Paint paint;
private Path path = new Path();
private int color;
public ColoredPath() {
paint = new Paint();
color = Color.BLACK;
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(4f);
paint.setAntiAlias(true);
paint.setColor(color);
}
public ColoredPath(int color) {
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(4f);
paint.setAntiAlias(true);
paint.setColor(color);
}
public void setColor(int color){
this.color = color;
}
public int getColor(){
return color;
}
public void setPaint(Paint paint){
this.paint = paint;
}
public Paint getPaint() {
return paint;
}
public void setPath(Path path){
this.path = path;
}
public Path getPath() {
return path;
}
}
DrawerView.java
public class DrawerView extends View {
public Path circlePath = new Path();
public static int LINE_COLOR = 0;
public static boolean isTouchable = false;
public List<ColoredPath> paths = new ArrayList<ColoredPath>();
public ColoredPath currentPath;
public DrawerView(Context context, AttributeSet attrs){
super(context, attrs);
currentPath = new ColoredPath();
paths.add(currentPath);
}
public void newLine(int color){
System.out.println("in newLine method");
currentPath = new ColoredPath(color);
paths.add(currentPath);
//postInvalidate();
}
public void onButtonPress(){
// resets the screen
currentPath.getPath().reset();
// Calls the onDraw() method
postInvalidate();
}
#Override
protected void onDraw(Canvas canvas) {
System.out.println("size of paths: "+paths.size());
canvas.drawPath(currentPath.getPath(), currentPath.getPaint());
for(int i = 0; i < paths.size(); ++i) {
//ColoredPath coloredPath = paths.get(i);
canvas.drawPath(currentPath.getPath(), currentPath.getPaint());
}
}
public Path getLastPath() {
Path path = new Path();
for(int i = 0; i < paths.size(); ++i) {
path.addPath(paths.get(i).getPath());
}
return path;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (!isTouchable){
return false;
} else {
// Gives you x and y coordinates on the Event.
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
currentPath.getPath().moveTo(pointX, pointY);
//getLastPath().moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
currentPath.getPath().lineTo(pointX, pointY);
//getLastPath().lineTo(pointX, pointY);
circlePath.reset();
circlePath.addCircle(pointX, pointY, 30, Path.Direction.CW);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
postInvalidate();
return true;
}
}
}
and in MainActivity.java
if (position == 1) {
// blue
myView.newLine(Color.BLUE);
d.dismiss();
}
this works well and colors the lines but when I select any color it leads to remove the last line and I want all lines with there colors.
Because Path itself doesn't contain any information about it's color (color is managed by Canvas) I would suggest you to create new pair of (Path, Paint) for every new path with different paint and use only current pair in onTouch event. So here is some code which illustrate this idea
public class ColoredPath {
private Paint paint;
private Path path;
public ColoredPath(Paint paint, Path path) {
this.paint = paint;
this.path = path;
}
public Paint getPaint() {
return paint;
}
public Path getPath() {
return path;
}
}
private List<ColoredPath> paths = new ArrayList<ColoredPath>();
public DrawerView(Context context, AttributeSet attrs){
super(context, attrs);
//custom paint can be used here
paths.add(new ColoredPath(new Paint(), new Path()));
}
/////
#Override
protected void onDraw(Canvas canvas) {
for(ColoredPath coloredPath : paths) {
canvas.drawPath(coloredPath.getPath(), coloredPath.getPaint());
}
}
Where paths is List<ColoredPath>. And also you need field like ColoredPath currentPath.

In CustomView, only alpha Animation doesn't work

I make my custom view. and I also make my custom view (making Circle). But In my custom view, Alpha Animation only don`t work....
My Customview extends linearlayout
public class mylayout extends FrameLayout implements View.OnClickListener {
......
public mylayout(Context context){
super(context);
init(context);
}
void init(Context context){
this.setLayoutParams(new
LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mButton = new Button(getContext());
mButton.setText("Delete all Created Circle.");
mButton.setId(10);
mButton.setOnClickListener(this);
bitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.change_sea01);
this.addView(mButton,new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
this.addView(new MyCircleView(getContext(), (int)event.getX(),
(int)event.getY()));
return true;
} else if(event.getAction() == MotionEvent.ACTION_MOVE) {
this.addView(new MyCircleView(getContext(),(int)event.getX(),
(int)event.getY()));
return true;
}
return super.onTouchEvent(event);
}
This is myCircle Class that make circle on touching point(x,y)
class MyCircleView extends ImageView{
.............
public MyCircleView(Context context, int xPos, int yPos) {
super(context);
pnt = new Paint();
pnt.setAntiAlias(true);
bDelete = false;
bmpCircle = BitmapFactory.decodeResource(context.getResources(),
R.drawable.img_click);
this.xPos = xPos;
this.yPos = yPos;
xWidth = bmpCircle.getWidth()/2;
yWidht = bmpCircle.getHeight()/2;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(setAnimation == null){
createAnimation(canvas);
}
canvas.drawBitmap(bmpCircle, xPos - xWidth, yPos - yWidht, pnt);
}
public void createAnimation(final Canvas canvas) {
AlphaAnimation alpha;
ScaleAnimation scale;
alpha = new AlphaAnimation(1.0f, 0.0f);
scale = new ScaleAnimation(1, 2, 1, 2, Animation.ABSOLUTE, xPos- xWidth,
Animation.ABSOLUTE, yPos - yWidht);
setAnimation = new AnimationSet(false);
setAnimation.addAnimation(alpha);
setAnimation.addAnimation(scale);
setAnimation.setDuration(3000);
startAnimation(setAnimation);
}
}

Categories

Resources