Use AlertDialog with canvas - android

I am using a .java which implements surfaceView to draw in the screen with canvas instead of using a .xml layout file, but I would like to know if somehow at some point (when what i do in the view is completed) its possible to associate this view with the layout file or to call a button or alerdialog.
To be clearer, something like when you win or fail in a game to show up an alerDialog like "you lose" or similar.
Main_Activity looks like:
public class Main extends Activity {
activity_layout_animation animation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
animation = new activity_layout_animation(this);
setContentView(animation);
}
#Override
protected void onPause(){
super.onPause();
animation.pause();
}
#Override
protected void onResume(){
super.onResume();
animation.resume();
}
Some piece of code of view file:
public class activity_layout_animation extends SurfaceView implements Runnable {
boolean CanDraw = false
public activity_layout_animation(Context context){
super(context);
surfaceHolder = getHolder();
}
#Override
public void run(){
while(CanDraw){
if ( !surfaceHolder.getSurface().isValid()){
continue;
}
}
}
edit: I can add somethig like this:
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
builder.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
but it just works in public activity_layout_animation(Context context){ and i want to add it in run()

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = activity.getLayoutInflater();
final View dialogCoordinate = inflater.inflate(R.layout.show_coordinates, null);
dialogBuilder.setCancelable(false);
dialogBuilder.setView(dialogCoordinate);
ImageView imgShowCoordinates = (ImageView) dialogCoordinate.findViewById(R.id.imgShowCoordinates);
imgShowCoordinates.setImageResource(R.drawable.whitetrans);
// int width = dmsUtility.getScreenSize(activity)[0];
// int height = dmsUtility.getScreenSize(activity)[1];
Log.d("Coordinate", "showCoordinates: "+arrayList.get(pos).getComment());
if (arrayList.get(pos).getComment() != null && !arrayList.get(pos).getComment().isEmpty()
&& !arrayList.get(pos).getComment().equals("null")) {
String[] parts1 = arrayList.get(pos).getComment().split("[\\s\\,]+");
Log.d(TAG, "getBody: " + arrayList.get(pos).getComment());
float[] numbers = new float[parts1.length];
for (int p = 0; p < numbers.length; p++) {
numbers[p] = Math.round(Float.parseFloat(parts1[p]) * 1000) / 1000f;
}
bmp = ((BitmapDrawable) imgShowCoordinates.getDrawable()).getBitmap();
if (bmp != null && !bmp.isRecycled()) {
Bitmap tempBitmap = Bitmap.createScaledBitmap(bmp, 300, 300, true);
tempCanvas = new Canvas(tempBitmap);
canW = tempBitmap.getWidth();
canH = tempBitmap.getHeight();
for (int q = 0; q < numbers.length; q = q + 4) {
float x1 = (canW / 300) * numbers[0 + q];
if (numbers.length > q + 2) {
Paint paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLUE); // Text Color
paint.setStrokeWidth(1f); // Text Size
paint.setAntiAlias(true);
float y1 = (canH / 300) * numbers[1 + q];
float x2 = (canW / 300) * numbers[2 + q];
float y2 = (canH / 300) * numbers[3 + q];
tempCanvas.drawLine(x1, y1, x2, y2, paint);
}
}
}
}
dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Related

calculate the area of shape created by custom lines on canvas in android

I am making an app for architecture planning. In that, i want to find the area covered by closed shape drawn by line on canvas by drawline() method. This is the Code.
public class CanvasBackground extends View {
public static boolean addPath;
public static flg flag;
public static boolean addLine = false;
public static boolean join = false;
public static boolean isDrawing;
public static int myLine;
public static ArrayList<Line> lines = new ArrayList<>();
public static ArrayList<Path> paths = new ArrayList<>();
public Paint paint;
public Context context;
public Canvas canvas;
public ScaleGestureDetector scaleGestureDetector;
public Bitmap addBtnBitmap;
public int passed_size;
float scalfactor = 1f;
Button addBtn;
public CanvasBackground(Context context) {
super(context);
this.context = context;
paint = new Paint();
scaleGestureDetector = new ScaleGestureDetector(context, new CanvasScale());
DrawingActivity drawingActivity = new DrawingActivity();
passed_size = drawingActivity.getCategory();
setDrawingCacheEnabled(true);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
canvas.save();
//add Button Select
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
DrawingZoomingCanvas(canvas);
DrawingLine(canvas);
canvas.restore();
Log.e("OnDraw >>>", "CALLING");
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (addLine) {
if (lines.size() != 0) {
Line current = lines.get(lines.size() - 1);
lines.add(new Line(current.stopX, current.stopY, myLine));
} else {
lines.add(new Line(event.getX(), event.getY(), myLine));
}
isDrawing = true;
addLine = false;
}
if (addPath) {
Path path = new Path();
path.moveTo(event.getX(), event.getY());
paths.add(path);
isDrawing = true;
addPath = false;
}
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (isDrawing) {
if (lines.size() > 0 && flg.ADDLINE == flag) {
Line current = lines.get(lines.size() - 1);
current.stopX = event.getX();
current.stopY = event.getY();
} else if (paths.size() > 0 && flg.ADDPATH == flag) {
Path path = paths.get(paths.size() - 1);
path.lineTo(event.getX(), event.getY());
}
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (isDrawing) {
if (lines.size() > 0 && flg.ADDLINE == flag) {
Line current = lines.get(lines.size() - 1);
current.stopX = event.getX();
current.stopY = event.getY();
}
invalidate();
}
break;
default:
break;
}
//scaleGestureDetector.onTouchEvent(event);
Log.e("OnTouch >>>", "CALLING " + isDrawing + " >> " + event.getX() + " >> " + event.getY() + ">>" + event.getAction());
return true;
}
//drawing a line
private void DrawingLine(Canvas canvas) {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
for (Line l : lines) {
canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
canvas.drawText(String.valueOf(l.getSize()), l.startX, l.startY, paint);
}
for (Path l : paths) {
canvas.drawPath(l, paint);
}
if (flg.JOIN == flag) {
Line first = lines.get(0);
Line last = lines.get(lines.size() - 1);
Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
canvas.drawText(String.valueOf(myLine), last.stopX, last.stopY, paint);
invalidate();
isDrawing = true;
}
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("CALL CLICK", "vv" + v.getId());
}
});
}
//drawing Matrix Canvas With Zoom
private void DrawingZoomingCanvas(Canvas canvas) {
//drawing Matarix
canvas.translate(scalfactor * 10, scalfactor * 10);
canvas.scale(scalfactor, scalfactor);
paint.setColor(Color.rgb(220, 220, 220));
for (int i = 0; i <= canvas.getHeight() * scalfactor; i += 10) {
canvas.drawLine(i, 0, i, canvas.getHeight(), paint);
canvas.drawLine(0, i, canvas.getWidth(), i, paint);
}
}
public void join_line() {
Line first = lines.get(0);
Line last = lines.get(lines.size() - 1);
Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
invalidate();
isDrawing = true;
}
public enum flg {ADDLINE, ADDPATH, JOIN}
private class CanvasScale extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scalfactor *= scaleGestureDetector.getScaleFactor();
scalfactor = Math.max(0.1f, Math.min(scalfactor, 10.0f));
invalidate();
return true;
}
}
}
This is the Activity.
public class DrawingActivity extends AppCompatActivity {
public int line_size;
CanvasBackground canvasBackground;
LinearLayout linearLayoutV, linearLayoutH;
Button addBtn, confirmBtn, clearBtn, addPath, joinbtn;
Context context = DrawingActivity.this;
LinearLayout.LayoutParams wrap_content_layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
canvasBackground = new CanvasBackground(context);
//Main Layout Liner
linearLayoutV = new LinearLayout(context);
linearLayoutV.setOrientation(LinearLayout.VERTICAL);
linearLayoutH = new LinearLayout(context);
linearLayoutH.setOrientation(LinearLayout.HORIZONTAL);
linearLayoutH.setWeightSum(4);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.weight = 1;
//add Line Button
addBtn = new Button(context);
addBtn.setLayoutParams(layoutParams);
addBtn.setText("Line+");
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CanvasBackground.addLine = true;
CanvasBackground.flag = CanvasBackground.flg.ADDLINE;
//**************** SET LENGTH
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Set the length of line");
builder1.setCancelable(true);
final EditText input = new EditText(DrawingActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder1.setView(input);
builder1.setPositiveButton(
"Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
line_size = Integer.parseInt(input.getText().toString());
Log.e("size", String.valueOf(getCategory()));
CanvasBackground.myLine = line_size;
dialog.cancel();
}
});
builder1.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
linearLayoutH.addView(addBtn);
// join last button
joinbtn = new Button(context);
joinbtn.setLayoutParams(layoutParams);
joinbtn.setText("Join");
joinbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CanvasBackground.flag = CanvasBackground.flg.JOIN;
v.invalidate();
//**************** SET LENGTH
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Set the length of line");
builder1.setCancelable(true);
final EditText input = new EditText(DrawingActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder1.setView(input);
builder1.setPositiveButton(
"Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
line_size = Integer.parseInt(input.getText().toString());
Log.e("size", String.valueOf(getCategory()));
CanvasBackground.myLine = line_size;
dialog.cancel();
}
});
builder1.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
linearLayoutH.addView(joinbtn);
//add Line Button
addPath = new Button(context);
addPath.setLayoutParams(layoutParams);
addPath.setText("Path+");
addPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CanvasBackground.addPath = true;
CanvasBackground.flag = CanvasBackground.flg.ADDPATH;
}
});
linearLayoutH.addView(addPath);
//add Confirm Button
confirmBtn = new Button(context);
confirmBtn.setLayoutParams(layoutParams);
confirmBtn.setText("Ok");
confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CanvasBackground.isDrawing = false;
}
});
linearLayoutH.addView(confirmBtn);
linearLayoutV.addView(linearLayoutH);
linearLayoutV.addView(canvasBackground);
setContentView(linearLayoutV);
}
public int getCategory() {
return line_size;
}
}
This is the whole code. Please help me.
Ya you can first validate the shape formed by the user on touch is close by observing the start and end coordinates. Once if the shape is closed. It forms a regular polygon.
For a regular polygon.
Find the perimeter of the polygon (permiter = summation of all side length)
Then find the apothem of the polygon ( apothem = length of sides / 2tan(180/no of sides))
Them find the area using the perimeter and the apothem.(Area = (area * perimeter)/2)
Also refer this link for more info on steps in detail.
http://www.wikihow.com/Find-the-Area-of-Regular-Polygons

Zoom image from its touch coordinates not from center

this is my code i m successfully zooming from center but i want to zoom in from the touch coordinates like instagram image zoom.I tried this code till now.Help me through it please.
ZoomImageActivity.java
public class ZoomImageActivity extends AppCompatActivity {
ImageView ivBG;
private ZoomImageHelper imageZoomHelper;
private View zoomableView = null;
View.OnTouchListener zoomTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
if (ev.getPointerCount() == 2 && zoomableView == null)
zoomableView = view;
break;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom_image);
ivBG = (ImageView) findViewById(R.id.ivBG);
ivBG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ivBG.setOnTouchListener(zoomTouchListener);
imageZoomHelper = new ZoomImageHelper(this, tvParam);
imageZoomHelper.addOnZoomListener(new ZoomImageHelper.OnZoomListener() {
#Override
public void onImageZoomStarted(View view) {
}
#Override
public void onImageZoomEnded(View view) {
zoomableView = null;
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return imageZoomHelper.onDispatchTouchEvent(ev, zoomableView) || super.dispatchTouchEvent(ev);
}}
ZoomImageHelper.java
public class ZoomImageHelper {
private View zoomableView = null;
private ViewGroup parentOfZoomableView;
private ViewGroup.LayoutParams zoomableViewLP;
private FrameLayout.LayoutParams zoomableViewFrameLP;
private Dialog dialog;
private View placeholderView;
private int viewIndex;
private View darkView;
private double originalDistance;
private int[] twoPointCenter;
private int[] originalXY;
private WeakReference<Activity> activityWeakReference;
private boolean isAnimatingDismiss = false;
private List<OnZoomListener> zoomListeners = new ArrayList<>();
public ZoomImageHelper(Activity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
public boolean onDispatchTouchEvent(MotionEvent ev, View view) {
Activity activity;
if ((activity = activityWeakReference.get()) == null)
return false;
if (ev.getPointerCount() == 2) {
if (zoomableView == null) {
if (view != null) {
zoomableView = view;
// get view's original location relative to the window
originalXY = new int[2];
view.getLocationInWindow(originalXY);
// this FrameLayout will be the zoomableView's temporary parent
FrameLayout frameLayout = new FrameLayout(view.getContext());
// this view is to gradually darken the backdrop as user zooms
darkView = new View(view.getContext());
darkView.setBackgroundColor(Color.BLACK);
darkView.setAlpha(0f);
// adding darkening backdrop to the frameLayout
frameLayout.addView(darkView, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// the Dialog that will hold the FrameLayout
dialog = new Dialog(activity,
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.addContentView(frameLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
dialog.show();
// get the parent of the zoomable view and get it's index and layout param
parentOfZoomableView = (ViewGroup) zoomableView.getParent();
viewIndex = parentOfZoomableView.indexOfChild(zoomableView);
this.zoomableViewLP = zoomableView.getLayoutParams();
// this is the new layout param for the zoomableView
zoomableViewFrameLP = new FrameLayout.LayoutParams(
view.getWidth(), view.getHeight());
zoomableViewFrameLP.leftMargin = originalXY[0];
zoomableViewFrameLP.topMargin = originalXY[1];
// this view will hold the zoomableView's position temporarily
placeholderView = new View(activity);
// setting placeholderView's background to zoomableView's drawingCache
// this avoids flickering when adding/removing views
zoomableView.setDrawingCacheEnabled(true);
BitmapDrawable placeholderDrawable = new BitmapDrawable(
activity.getResources(),
Bitmap.createBitmap(zoomableView.getDrawingCache()));
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(placeholderDrawable);
} else {
placeholderView.setBackgroundDrawable(placeholderDrawable);
}
// placeholderView takes the place of zoomableView temporarily
parentOfZoomableView.addView(placeholderView, zoomableViewLP);
// zoomableView has to be removed from parent view before being added to it's
// new parent
parentOfZoomableView.removeView(zoomableView);
frameLayout.addView(zoomableView, zoomableViewFrameLP);
// using a post to remove placeholder's drawing cache
zoomableView.post(new Runnable() {
#Override
public void run() {
if (dialog != null) {
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(null);
} else {
placeholderView.setBackgroundDrawable(null);
}
zoomableView.setDrawingCacheEnabled(false);
}
}
});
// Pointer variables to store the original touch positions
MotionEvent.PointerCoords pointerCoords1 = new MotionEvent.PointerCoords();
ev.getPointerCoords(0, pointerCoords1);
MotionEvent.PointerCoords pointerCoords2 = new MotionEvent.PointerCoords();
ev.getPointerCoords(1, pointerCoords2);
// storing distance between the two positions to be compared later on for
// zooming
originalDistance = (int) getDistance(pointerCoords1.x, pointerCoords2.x,
pointerCoords1.y, pointerCoords2.y);
// storing center point of the two pointers to move the view according to the
// touch position
twoPointCenter = new int[]{
(int) ((pointerCoords2.x + pointerCoords1.x) / 2),
(int) ((pointerCoords2.y + pointerCoords1.y) / 2)
};
sendZoomEventToListeners(zoomableView, true);
return true;
}
} else {
MotionEvent.PointerCoords pointerCoords1 = new MotionEvent.PointerCoords();
ev.getPointerCoords(0, pointerCoords1);
MotionEvent.PointerCoords pointerCoords2 = new MotionEvent.PointerCoords();
ev.getPointerCoords(1, pointerCoords2);
int[] newCenter = new int[]{
(int) ((pointerCoords2.x + pointerCoords1.x) / 2),
(int) ((pointerCoords2.y + pointerCoords1.y) / 2)
};
int currentDistance = (int) getDistance(pointerCoords1.x, pointerCoords2.x,
pointerCoords1.y, pointerCoords2.y);
double pctIncrease = (currentDistance - originalDistance) / originalDistance;
zoomableView.setScaleX((float) (1 + pctIncrease));
zoomableView.setScaleY((float) (1 + pctIncrease));
updateZoomableViewMargins(newCenter[0] - twoPointCenter[0] + originalXY[0],
newCenter[1] - twoPointCenter[1] + originalXY[1]);
darkView.setAlpha((float) (pctIncrease / 8));
return true;
}
} else {
if (zoomableView != null && !isAnimatingDismiss) {
isAnimatingDismiss = true;
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f);
valueAnimator.setDuration(activity.getResources()
.getInteger(android.R.integer.config_shortAnimTime));
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
float scaleYStart = zoomableView.getScaleY();
float scaleXStart = zoomableView.getScaleX();
int leftMarginStart = zoomableViewFrameLP.leftMargin;
int topMarginStart = zoomableViewFrameLP.topMargin;
float alphaStart = darkView.getAlpha();
float scaleYEnd = 1f;
float scaleXEnd = 1f;
int leftMarginEnd = originalXY[0];
int topMarginEnd = originalXY[1];
float alphaEnd = 0f;
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedFraction = valueAnimator.getAnimatedFraction();
if (animatedFraction < 1) {
zoomableView.setScaleX(((scaleXEnd - scaleXStart) * animatedFraction) +
scaleXStart);
zoomableView.setScaleY(((scaleYEnd - scaleYStart) * animatedFraction) +
scaleYStart);
updateZoomableViewMargins(
((leftMarginEnd - leftMarginStart) * animatedFraction) +
leftMarginStart,
((topMarginEnd - topMarginStart) * animatedFraction) +
topMarginStart);
darkView.setAlpha(((alphaEnd - alphaStart) * animatedFraction) +
alphaStart);
} else {
dismissDialogAndViews();
}
}
});
valueAnimator.start();
return true;
}
}
return false;
}
void updateZoomableViewMargins(float left, float top) {
if (zoomableView != null && zoomableViewFrameLP != null) {
zoomableViewFrameLP.leftMargin = (int) left;
zoomableViewFrameLP.topMargin = (int) top;
zoomableView.setLayoutParams(zoomableViewFrameLP);
}
}
/**
* Dismiss dialog and set views to null for garbage collection
*/
private void dismissDialogAndViews() {
sendZoomEventToListeners(zoomableView, false);
if (zoomableView != null) {
zoomableView.setVisibility(View.VISIBLE);
zoomableView.setDrawingCacheEnabled(true);
BitmapDrawable placeholderDrawable = new BitmapDrawable(
zoomableView.getResources(),
Bitmap.createBitmap(zoomableView.getDrawingCache()));
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(placeholderDrawable);
} else {
placeholderView.setBackgroundDrawable(placeholderDrawable);
}
ViewGroup parent = (ViewGroup) zoomableView.getParent();
parent.removeView(zoomableView);
this.parentOfZoomableView.addView(zoomableView, viewIndex, zoomableViewLP);
this.parentOfZoomableView.removeView(placeholderView);
zoomableView.setDrawingCacheEnabled(false);
zoomableView.post(new Runnable() {
#Override
public void run() {
dismissDialog();
}
});
zoomableView = null;
} else {
dismissDialog();
}
isAnimatingDismiss = false;
}
public void addOnZoomListener(OnZoomListener onZoomListener) {
zoomListeners.add(onZoomListener);
}
public void removeOnZoomListener(OnZoomListener onZoomListener) {
zoomListeners.remove(onZoomListener);
}
private void sendZoomEventToListeners(View zoomableView, boolean zoom) {
for (OnZoomListener onZoomListener : zoomListeners) {
if (zoom)
onZoomListener.onImageZoomStarted(zoomableView);
else
onZoomListener.onImageZoomEnded(zoomableView);
}
}
private void dismissDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
darkView = null;
resetOriginalViewAfterZoom();
}
private void resetOriginalViewAfterZoom() {
zoomableView.invalidate();
zoomableView = null;
}
/**
* Get distance between two points
*
* #param x1
* #param x2
* #param y1
* #param y2
* #return distance
*/
private double getDistance(double x1, double x2, double y1, double y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
public interface OnZoomListener {
void onImageZoomStarted(View view);
void onImageZoomEnded(View view);
}}
I need the image to zoom and pan from its touch coordinates not from center.. Thanks in advance.

Android Rebound translate up animation

I have popupWindow with some image views, which are created and added progammatically to popup window. Their position is set to bottom line with setY(). But when I use setEndValue to animate with spring, image goes from 0 to setEndValue, not from it's initial position.
How that can be fixed?
public SharePostPopupWindow(View parentView) {
super(MATCH_PARENT, MATCH_PARENT);
this.context = parentView.getContext();
this.parentView = parentView;
AndroidBlaBlaApplication.component(context).inject(this);
setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
FrameLayout container = new FrameLayout(context);
socialViews = new ArrayList<>();
socials = new ArrayList<>();
shadow = new View(context);
shadow.setId(R.id.share_view_shadow);
shadow.setBackgroundColor(Color.BLACK);
shadow.setClickable(true);
shadow.setAlpha(0.5f);
shadow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bus.post(new ShadowClickedEvent());
spring.setEndValue(initialPosition / 2 - Utils.convertDpToPixel(imageSize, context));
dismiss();
}
});
}
public void show() {
Utils.hideKeyboard(context, getContentView());
createButtons();
SpringSystem springSystem = SpringSystem.create();
spring = springSystem.createSpring();
SpringConfig slowConfig = new SpringConfig(TENSION, DAMPER);
spring.setSpringConfig(slowConfig);
spring.addListener(new SimpleSpringListener() {
#Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
for (int i = 0; i < socialViews.size(); i++) {
if (i % 2 != 0) {
socialViews.get(i).setY(value);
}
}
}
});
showAtLocation(parentView, Gravity.CENTER_VERTICAL, 0, 0);
getContentView().setAlpha(1f);
}
If you want to force spring animation from certain position, you need to use
spring.setCurrentValue method first.

LiveWallpaper Background

i have problem with live wallpaper on preview mode.ie the wallpaper image doesn't fit well in landscape mode.it works great on portrait.i need your help.hope you would help me.i have added code
RajawaliRenderer.java
public class RipplesRenderer extends RajawaliRenderer {
private final int NUM_CUBES_H = 4;
private final int NUM_CUBES_V = 4;
private final int NUM_CUBES = NUM_CUBES_H * NUM_CUBES_V;
//private Animation3D[] mAnims;
private TouchRippleFilter mFilter;
private long frameCount;
private final int QUAD_SEGMENTS = 40;
int mScreenHeight,
mScreenWeight;
Gallery_Activity mm;
boolean flag_check = false;
int pos = 0;
int viewBackgroundImageName;
Bitmap texture;
SimpleMaterial planeMat;
int randPosition=1;
int change_value;
int Ripple_number,speed1;
Preferences preferences;
private MediaPlayer myplayer;
private boolean sound;
public RipplesRenderer(Context context) {
super(context);
setFrameRate(50);
this.mContext=context;
randPosition = BitmapUpdate.randomGenerator;
texture = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gthree_one);
//sp=mContext.getSharedPreferences("wallpapersettings",0);
preferences=new Preferences(mContext);
}
protected void initScene() {
if(randPosition!=1) {
texture = BitmapUpdate.bit;
}
mCamera.setPosition(0, 0, -9);
DirectionalLight light = new DirectionalLight(0, 0, 1);
light.setPower(1f);
BaseObject3D group = new BaseObject3D();
DiffuseMaterial material = new DiffuseMaterial();
material.setUseColor(true);
mScreenHeight = GNWallpaper.hieght;
mScreenWeight = GNWallpaper.weight;
Random rnd = new Random();
planeMat = new SimpleMaterial();
Plane plane=new Plane(9,7,1,1);
//Plane plane = new Plane(4, 4, 1, 1);
plane.setRotZ(-90);
plane.setScale(1.0f);
plane.setMaterial(planeMat);
addChild(plane);
mFilter = new TouchRippleFilter();
mPostProcessingRenderer.setQuadSegments(QUAD_SEGMENTS);
mPostProcessingRenderer.setQuality(PostProcessingQuality.MEDIUM);
addPostProcessingFilter(mFilter);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (pos != com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position || randPosition != BitmapUpdate.randomGenerator) {
texture = BitmapUpdate.bit;
pos = com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position;
randPosition = BitmapUpdate.randomGenerator;
}
Ripple_number=preferences.getSpeed_controler();
speed1=Ripple_number*100;
super.onSurfaceCreated(gl, config);
}
public void onDrawFrame(GL10 glUnused) {
super.onDrawFrame(glUnused);
mFilter.setTime((float) frameCount++ *.05f);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
super.onSurfaceChanged(gl, width, height);
mFilter.setScreenSize(width, height);
mFilter.setRippleSize((40+speed1));
planeMat.addTexture(mTextureManager.addTexture(texture));
}
public void setTouch(float x, float y) {
mFilter.addTouch(x, y, frameCount *.05f);
}
#Override
public void onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//sound
myplayer = MediaPlayer.create(getContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
myplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer myplayer) {
myplayer.release();
}
});
setTouch(event.getX() / mScreenWeight, 1.0f - (event.getY() / mScreenHeight));
}
super.onTouchEvent(event);
}
}
Settings.java
public class Settings extends Activity {
public TextView SettingTextObj, BackgroundTextObj;
private RelativeLayout chose_background;
public Preferences preferences;
Context cont = this;
private CheckBox soundcheckbox;
private String PREFRENCES_NAME;
SharedPreferences settings;
// private Button choosebackground;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
chose_background = (RelativeLayout) findViewById(R.id.BackgroundLayoutId);
BackgroundTextObj = (TextView) findViewById(R.id.backgroundTxtViewId);
soundcheckbox = (CheckBox)findViewById(R.id.checkBox1);
settings = getSharedPreferences(PREFRENCES_NAME, 0);
Boolean isChecked = settings.getBoolean("cbx1_ischecked", false);
soundcheckbox.setChecked(isChecked);
soundcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private MediaPlayer myplayer;
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Editor editor = getSharedPreferences(PREFRENCES_NAME, 0).edit();
editor.putBoolean("cbx1_ischecked", isChecked);
editor.commit();
Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
myplayer = MediaPlayer.create(getBaseContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
}
});
preferences = new Preferences(cont);
chose_background.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String[] items = { "Phone Gallery", "Choose Background" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Settings.this);
builder.setTitle("Pick a Background");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
startActivity(new Intent(Settings.this, PhoneGallery_Activity.class));
} else {
startActivity(new Intent(Settings.this, Gallery_Activity.class));
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
GNWallpaper.java
public class GNWallpaper extends Wallpaper {
private RipplesRenderer mRenderer;
private String imageBg;
private int cvwidth;
private int cvheight;
private int visibleWidth;
private Bitmap bg;
private String LoadText;
private boolean sound;
private MediaPlayer myplayer;
public static WindowManager display;
static int height,width;
//private Integer[] mImageIds = { R.drawable.gthree_one,R.drawable.gthree_two,R.drawable.gthree_three, R.drawable.gthree_four, R.drawable.gthree_five, R.drawable.gthree_six,};
private int position;
public Engine onCreateEngine() {
display =(WindowManager) getSystemService(Context.WINDOW_SERVICE);
height= display.getDefaultDisplay().getHeight();
width= display.getDefaultDisplay().getWidth();
mRenderer = new RipplesRenderer(this);
//Log.i("shibbu"," hello");
return new WallpaperEngine(this.getSharedPreferences(SHARED_PREFS_NAME,
Context.MODE_PRIVATE), getBaseContext(), mRenderer, false);
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
imageBg = prefs.getString("image_custom", "Bad Image");
getBackground();
sound=prefs.getBoolean("pref_sound", false);
// //sound
// sound=prefs.getBoolean("pref_sound", false);
}
void getBackground() {
if (this.cvwidth == 0 || this.cvheight == 0 || this.visibleWidth == 0) {
this.cvwidth = 1290;
this.cvheight = 800;
this.visibleWidth = 1290;
}
if(new File(imageBg).exists()) {
int SampleSize = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bg = BitmapFactory.decodeFile(imageBg, options);
SampleSize = (int) (Math.ceil(options.outWidth/(this.visibleWidth * 2))*2);
options.inJustDecodeBounds = false;
try {
options.inSampleSize = SampleSize;
bg = BitmapFactory.decodeFile(imageBg, options);
} catch (OutOfMemoryError e) {
SampleSize = SampleSize * 2;
}
} while (bg == null);
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
} else {
bg = BitmapFactory.decodeResource(getResources(), R.drawable.gthree_one);
//bg = BitmapFactory.decodeResource(getResources(), mImageIds[position]);
//position++;
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
LoadText = "";
}
}
}
Refer this link.It will help you to change to landscape view..
http://tips4android.blogspot.in/2012/01/android-tips-how-to-get-screen.html

Multiple edittexts using textwatchers

So I have a view that has two edit texts that are using textwatchers as text change listeners. when the value from first edit text is changed a new value is calculated and set to the 2nd edit text and vice versa. I am removing the textwatchers before setting the text. the problem I am facing is when I type something in the first or the second edit text box it takes only one or two numbers and stops taking any input. the cursor goes from the end to the start. here is the class
public class CurrencyView extends RelativeLayout implements ICustomView{
private class CustomOnClick implements OnClickListener{
#Override
public void onClick(View v) {
final TextView view = (TextView)v;
final String options[] = ConversionTypes.getCurrencyTypes();
AlertDialog.Builder builder = new AlertDialog.Builder(rContext);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
view.setText(options[which]);
convert(view.getId());
}
});
builder.show();
}
}
private class CustomTextWatcher implements TextWatcher{
int ID;
#Override
public void afterTextChanged(Editable s) {
convert(ID);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if(s.toString().equals(type1Value.getText().toString())){
ID=11;
}
else{
ID=22;
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
}
private TextView currencyType1;
private LayoutParams currencyType1LP;
private TextView currencyType2;
private LayoutParams currencyType2LP;
private EditText type1Value;
private LayoutParams type1ValueLP;
private EditText type2Value;
private LayoutParams type2ValueLP;
private CustomTextWatcher fCustomTextWatcher = new CustomTextWatcher();
private ArrayList<Double> rates = new ArrayList<Double>();
private Context rContext;
private int screenWidth;
private ListView rPopularConversions;
private long lastRefreshed;
private TextView lastRefeshedView;
private void addListeners() {
currencyType1.setOnClickListener(new CustomOnClick());
currencyType2.setOnClickListener(new CustomOnClick());
addEditTextListeners();
}
private void addEditTextListeners() {
type1Value.addTextChangedListener(fCustomTextWatcher);
type2Value.addTextChangedListener(fCustomTextWatcher);
}
private void convert(int i) {
removeAllListeners();
if(i == 11 || i == 1 ){
if(!Formatting.isEmptyOrNull(type2Value)){
double from = rates.get(getLocation(currencyType2));
double to = rates.get(getLocation(currencyType1));
Currency c = new Currency(from,to, Double.valueOf(type2Value.getText().toString()));
type1Value.setText(String.valueOf(Formatting.roundOff(c.getResult())));
}
}
if(i == 22 || i==2 ){
if(!Formatting.isEmptyOrNull(type1Value)){
double from = rates.get(getLocation(currencyType1));
double to = rates.get(getLocation(currencyType2));
Currency c = new Currency(from, to, Double.valueOf(type1Value.getText().toString()));
type2Value.setText(String.valueOf(Formatting.roundOff(c.getResult())));
}
}
addEditTextListeners();
}
private int getLocation(TextView tv) {
for (int i = 0; i < ConversionTypes.getCurrencyTypes().length; i++) {
if(tv.getText().toString().equals(ConversionTypes.getCurrencyTypes()[i])){
return i;
}
}
return 0;
}
private void initialize() {
currencyType1 = CustomObject.getCustomTextView(rContext, 1, Color.parseColor("#63879F"), Color.WHITE, 16, ConversionTypes.getCurrencyTypes()[121]);
currencyType2 = CustomObject.getCustomTextView(rContext, 2, Color.parseColor("#63879F"), Color.WHITE, 16, ConversionTypes.getCurrencyTypes()[121]);
type1Value = CustomObject.getCustomInputBox(rContext, 35, "1", "Enter value", new int[]{}, 11);
type1Value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
type2Value = CustomObject.getCustomInputBox(rContext, 35, "1", "Enter value", new int[]{}, 22);
type2Value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
int orientation = ((WindowManager) rContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {
loadPotraitView();
}
else {
loadLandscapeView();
}
}
#Override
public void loadLandscapeView() {
lastRefreshed = rContext.getSharedPreferences("com.rokzin.converto_preferences", 0).getLong("LastRefreshed", 0);
screenWidth = rContext.getResources().getDisplayMetrics().widthPixels;
removeAllViews();
rPopularConversions = new ListView(rContext);
RelativeLayout.LayoutParams listLP = CustomObject.getCustomParams(screenWidth, LayoutParams.WRAP_CONTENT, new int[]{});
listLP.addRule(RelativeLayout.BELOW, type2Value.getId());
currencyType1LP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.ALIGN_PARENT_TOP});
currencyType2LP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.ALIGN_PARENT_TOP});
type1ValueLP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT});
type2ValueLP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_RIGHT});
type1ValueLP.addRule(RelativeLayout.BELOW, currencyType1.getId());
type2ValueLP.addRule(RelativeLayout.BELOW, currencyType2.getId());
this.addView(currencyType1, currencyType1LP);
TextView equalTo = CustomObject.getCustomTextView(rContext, 111, Color.TRANSPARENT, Color.parseColor("#63879F"), 24, "=");
RelativeLayout.LayoutParams params = CustomObject.getCustomParams(screenWidth*2/20, 240, new int[]{RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.CENTER_HORIZONTAL});
equalTo.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
this.addView(equalTo, params);
this.addView(currencyType2, currencyType2LP);
this.addView(type1Value,type1ValueLP);
this.addView(type2Value,type2ValueLP);
this.addView(rPopularConversions,listLP);
removeAllListeners();
addListeners();
}
#Override
public void loadPotraitView() {
lastRefreshed = rContext.getSharedPreferences("com.rokzin.converto_preferences", 0).getLong("LastRefreshed", 0);
screenWidth = rContext.getResources().getDisplayMetrics().widthPixels;
removeAllViews();
rPopularConversions = new ListView(rContext);
RelativeLayout.LayoutParams listLP = CustomObject.getCustomParams(screenWidth, LayoutParams.WRAP_CONTENT, new int[]{});
listLP.addRule(RelativeLayout.BELOW, currencyType2.getId());
currencyType1LP = CustomObject.getCustomParams(screenWidth * 1/3, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.ALIGN_PARENT_TOP});
currencyType2LP = CustomObject.getCustomParams(screenWidth * 1/3, 120, new int[]{});
type1ValueLP = CustomObject.getCustomParams(screenWidth * 2/3, 120, new int[]{RelativeLayout.ALIGN_PARENT_TOP});
type2ValueLP = CustomObject.getCustomParams(screenWidth * 2/3, 120, new int[]{});
type1ValueLP.addRule(RelativeLayout.RIGHT_OF, currencyType1.getId());
type2ValueLP.addRule(RelativeLayout.BELOW, currencyType1.getId());
currencyType2LP.addRule(RelativeLayout.RIGHT_OF, type2Value.getId());
currencyType2LP.addRule(RelativeLayout.BELOW, type1Value.getId());
this.addView(currencyType1, currencyType1LP);
this.addView(type1Value,type1ValueLP);
this.addView(type2Value,type2ValueLP);
this.addView(currencyType2, currencyType2LP);
this.addView(rPopularConversions,listLP);
removeAllListeners();
addListeners();
}
public void removeAllListeners(){
type1Value.removeTextChangedListener(fCustomTextWatcher);
type2Value.removeTextChangedListener(fCustomTextWatcher);
}
}
I think the problem is here:
if(s.toString().equals(type1Value.getText().toString())){
ID=11;
}
else{
ID=22;
}
Take in mind that both EditTexts are going through that method, so when type1Value is being edited, s.toString().equals(type1Value.getText().toString()) will be true.
I recommend you to use a TextWatcher for each EditText so you won't have to differentiate each one.

Categories

Resources