How to make dialog visible when touch anywhere on screen? - android

I want to make my dialog visible when i touch everywhere on the display.
I have an Activity, a view and a Renderer class. I wrote my code in the View class:
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {....}}
I posted my code. (Only activity and View)
public class MapEditorActivity extends Activity {
private GLSurfaceView mGLSurfaceView;
Region dialogRegion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Create our Preview view and set it as the content of our
// Activity
mGLSurfaceView = new MapEditorView(this);
setContentView(mGLSurfaceView);
}
#Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
}
}
And my View class:
public class MapEditorView extends GLSurfaceView {
private static final String LOG_TAG = "de.rwth.arlab.colofields.ui.MapEditorView";
MapEditorRenderer editMapRenderer;
// we have a maximum of 5 pointer
private int[] coordsX = new int[5];
private int[] coordsY = new int[5];
// we have to save first touch for motion
private int[] coordsXFirst = new int[5];
private int[] coordsYFirst = new int[5];
// offsets for view
private float offX;
private float offY;
private float offZ;
Context context;
boolean zooming;
public MapEditorView(Context context) {
super(context);
editMapRenderer = new MapEditorRenderer(context);
setRenderer(editMapRenderer);
// initialize as not present
Arrays.fill(coordsX, Integer.MIN_VALUE);
Arrays.fill(coordsY, Integer.MIN_VALUE);
zooming = false;
}
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {
// TODO: Speak about this thing, this functions need API8
#SuppressLint("NewApi")
public void run() {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
offX = editMapRenderer.getxView();
offY = editMapRenderer.getyView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
startDialog(null);
break;
case MotionEvent.ACTION_POINTER_DOWN:
offZ = editMapRenderer.getzView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
coordsXFirst[1] = (int) event.getX(1);
coordsYFirst[1] = (int) event.getY(1);
zooming=true;
break;
case MotionEvent.ACTION_UP:
zooming=false;
break;
default:
// track all touches
for (int i = 0; i < event.getPointerCount(); i++) {
int id = event.getPointerId(i);
// update all other pointer positions
coordsX[id] = (int) event.getX(i);
coordsY[id] = (int) event.getY(i);
}
// When only one finger
if (event.getPointerCount() == 1 && !zooming)
editMapRenderer.setPosition(offX
+ (coordsX[0] - coordsXFirst[0])*editMapRenderer.getzView()*-1 / 1000.0f, offY
+ (coordsYFirst[0] - coordsY[0])*editMapRenderer.getzView()*-1 / 1000.0f);
// When two fingers
float distanceOld = (float) FloatMath
.sqrt((coordsXFirst[1] - coordsXFirst[0])
* (coordsXFirst[1] - coordsXFirst[0])
+ (coordsYFirst[1] - coordsYFirst[0])
* (coordsYFirst[1] - coordsYFirst[0]));
float distanceNew = (float) FloatMath
.sqrt((coordsX[1] - coordsX[0])
* (coordsX[1] - coordsX[0])
+ (coordsY[1] - coordsY[0])
* (coordsY[1] - coordsY[0]));
float distanceMax = (float) FloatMath
.sqrt(getWidth()
* getWidth()
+ getHeight()
* getHeight());
if (event.getPointerCount() == 2) {
editMapRenderer.setZoom(offZ + (distanceNew
- distanceOld)/(distanceMax/10));
}
break;
}
}
public Dialog startDialog(Bundle savedInstanceState) {
final CharSequence[] items = new String[] { "#F5F6F6", "#FFC0CB", "#FF0000",
"#C00000","#62492F","#DB3C00", "#98E01C" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText((Context) getApplicationWindowToken(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
}
});
return true;
}
MapEditorRenderer mRenderer;
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater =((Activity)context).getMenuInflater();
inflater.inflate(R.layout.menu_save, menu);
return true;
}
}
My problem is the method startDialog().
It does not work. I get an error:
"The constructor AlertDialog.Builder(new Runnable(){}) is undefined"
How can i solve it?
Ok i post again my code :
>
public class MapEditorActivity extends Activity {
private GLSurfaceView mGLSurfaceView;
Region dialogRegion;
MapEditorRenderer editMapRenderer;
// we have a maximum of 5 pointer
private int[] coordsX = new int[5];
private int[] coordsY = new int[5];
// we have to save first touch for motion
private int[] coordsXFirst = new int[5];
private int[] coordsYFirst = new int[5];
// offsets for view
private float offX;
private float offY;
private float offZ;
Context context;
boolean zooming;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Create our Preview view and set it as the content of our
// Activity
mGLSurfaceView = new MapEditorView(this);
setContentView(mGLSurfaceView);
mGLSurfaceView.setOnTouchListener(MapEditorActivity.this);
}
#Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
}
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {
// TODO: Speak about this thing, this functions need API8
#SuppressLint("NewApi")
public void run() {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
offX = editMapRenderer.getxView();
offY = editMapRenderer.getyView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
startDialog(null);
break;
case MotionEvent.ACTION_POINTER_DOWN:
offZ = editMapRenderer.getzView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
coordsXFirst[1] = (int) event.getX(1);
coordsYFirst[1] = (int) event.getY(1);
zooming=true;
break;
case MotionEvent.ACTION_UP:
zooming=false;
break;
default:
// track all touches
for (int i = 0; i < event.getPointerCount(); i++) {
int id = event.getPointerId(i);
// update all other pointer positions
coordsX[id] = (int) event.getX(i);
coordsY[id] = (int) event.getY(i);
}
// When only one finger
if (event.getPointerCount() == 1 && !zooming)
editMapRenderer.setPosition(offX
+ (coordsX[0] - coordsXFirst[0])*editMapRenderer.getzView()*-1 / 1000.0f, offY
+ (coordsYFirst[0] - coordsY[0])*editMapRenderer.getzView()*-1 / 1000.0f);
// When two fingers
float distanceOld = (float) FloatMath
.sqrt((coordsXFirst[1] - coordsXFirst[0])
* (coordsXFirst[1] - coordsXFirst[0])
+ (coordsYFirst[1] - coordsYFirst[0])
* (coordsYFirst[1] - coordsYFirst[0]));
float distanceNew = (float) FloatMath
.sqrt((coordsX[1] - coordsX[0])
* (coordsX[1] - coordsX[0])
+ (coordsY[1] - coordsY[0])
* (coordsY[1] - coordsY[0]));
float distanceMax = (float) FloatMath
.sqrt(getWidth()
* getWidth()
+ getHeight()
* getHeight());
if (event.getPointerCount() == 2) {
editMapRenderer.setZoom(offZ + (distanceNew
- distanceOld)/(distanceMax/10));
}
break;
}
}
private int getHeight() {
// TODO Auto-generated method stub
return 0;
}
private int getWidth() {
// TODO Auto-generated method stub
return 0;
}
public Dialog startDialog(Bundle savedInstanceState) {
final CharSequence[] items = new String[] { "#F5F6F6", "#FFC0CB", "#FF0000",
"#C00000","#62492F","#DB3C00", "#98E01C" };
AlertDialog.Builder builder = new AlertDialog.Builder(MapEditorActivity.this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText((Context) getApplication(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
return alert;
}
});
return true;
}
private void queueEvent(Runnable runnable) {
// TODO Auto-generated method stub
}
MapEditorRenderer mRenderer;
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater =((Activity)context).getMenuInflater();
inflater.inflate(R.layout.menu_save, menu);
return true;
}
}

Replace
AlertDialog.Builder builder = new AlertDialog.Builder(this);
with
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
and your problem will be solved.

Replace
AlertDialog.Builder builder = new AlertDialog.Builder(this);
with
AlertDialog.Builder builder = new AlertDialog.Builder(MapEditorView.this.getContext());

Write below code line
builder.show();
instead of
AlertDialog alert = builder.create();
it will solve your problem.

Ok guys, i have changed my code. This is the last version.but i have stimm the same problem.
public class MapEditorActivity extends Activity implements OnTouchListener{
private GLSurfaceView mGLSurfaceView;
MapEditorRenderer editMapRenderer;
// we have a maximum of 5 pointer
private int[] coordsX = new int[5];
private int[] coordsY = new int[5];
// we have to save first touch for motion
private int[] coordsXFirst = new int[5];
private int[] coordsYFirst = new int[5];
// offsets for view
private float offX;
private float offY;
private float offZ;
Context context;
boolean zooming;
Region dialogRegion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Create our Preview view and set it as the content of our
// Activity
mGLSurfaceView = new MapEditorView(this);
setContentView(mGLSurfaceView);
mGLSurfaceView.setOnTouchListener(MapEditorActivity.this);
}
private void showDialog(){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
final String[] color = { "#F5F6F6", "#FFC0CB", "#FF0000",
"#C00000","#62492F","#DB3C00", "#98E01C" };
dialogBuilder.setTitle("pick one Color");
dialogBuilder.setItems(color, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),color[which], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
#Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
offX = editMapRenderer.getxView();
offY = editMapRenderer.getyView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
showDialog();
break;
case MotionEvent.ACTION_POINTER_DOWN:
offZ = editMapRenderer.getzView();
coordsXFirst[0] = (int) event.getX(0);
coordsYFirst[0] = (int) event.getY(0);
coordsXFirst[1] = (int) event.getX(1);
coordsYFirst[1] = (int) event.getY(1);
zooming=true;
break;
case MotionEvent.ACTION_UP:
zooming=false;
break;
default:
// track all touches
for (int i = 0; i < event.getPointerCount(); i++) {
int id = event.getPointerId(i);
// update all other pointer positions
coordsX[id] = (int) event.getX(i);
coordsY[id] = (int) event.getY(i);
}
// When only one finger
if (event.getPointerCount() == 1 && !zooming)
editMapRenderer.setPosition(offX
+ (coordsX[0] - coordsXFirst[0])*editMapRenderer.getzView()*-1 / 1000.0f, offY
+ (coordsYFirst[0] - coordsY[0])*editMapRenderer.getzView()*-1 / 1000.0f);
// When two fingers
float distanceOld = (float) FloatMath
.sqrt((coordsXFirst[1] - coordsXFirst[0])
* (coordsXFirst[1] - coordsXFirst[0])
+ (coordsYFirst[1] - coordsYFirst[0])
* (coordsYFirst[1] - coordsYFirst[0]));
float distanceNew = (float) FloatMath
.sqrt((coordsX[1] - coordsX[0])
* (coordsX[1] - coordsX[0])
+ (coordsY[1] - coordsY[0])
* (coordsY[1] - coordsY[0]));
float distanceMax = (float) FloatMath
.sqrt(getWidth()
* getWidth()
+ getHeight()
* getHeight());
if (event.getPointerCount() == 2) {
editMapRenderer.setZoom(offZ + (distanceNew
- distanceOld)/(distanceMax/10));
}
break;
}
return false;
}
private int getHeight() {
// TODO Auto-generated method stub
return 0;
}
private int getWidth() {
// TODO Auto-generated method stub
return 0;
}
}

Related

Auto moving TextView across the screen

I am trying to make TextView which moves across the screen in all directions randomly using translateAnimation. I need text moving like in screen saver for example going round and round until it is clicked.But have some problems:
1. text moves just from top to bottom
2.it doesn't stop in screen borders , it is going off the screen then coming back again :
public class aktivityStarted extends AppCompatActivity {
TextView textMovin;
/* int loc[]=new int[2];
int x=loc[0];
int y=loc[1];*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aktivity_started);
textMovin=findViewById(R.id.movingText);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int width = displaymetrics.widthPixels-textMovin.getWidth();
final int height = displaymetrics.heightPixels-textMovin.getHeight();
final Random r = new Random();
final int translationX = r.nextInt(width);
final int translationY = r.nextInt(height);
final int randomx=r.nextInt(50)+1;
final int randomy=r.nextInt(50)+1;
final TranslateAnimation anim = new TranslateAnimation(-translationX,translationX ,-translationY,translationY ); //Use current view position instead of `currentX` and `currentY`
anim.setDuration(2500);
anim.setRepeatCount(-1);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
anim.reset();
anim.setRepeatMode(Animation.REVERSE);
anim.setFillAfter(true);
}
#Override
public void onAnimationRepeat(Animation animation) {
textMovin.setY(r.nextInt(height));
textMovin.setX(r.nextInt(width));
anim.start();
}
});
textMovin.startAnimation(anim);
}
}
try this code:
public class MainActivity extends AppCompatActivity {
private View parent;
private TextView textMovin;
private float speedX;
private float speedY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMovin = findViewById(R.id.textV);
parent = findViewById(R.id.parent);
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
final int width = parent.getWidth() - textMovin.getWidth();
final int height = parent.getHeight() - textMovin.getHeight();
final int period = 50;
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
textMovin.post(new TimerTask() {
#Override
public void run() {
textMovin.setX(speedX * period / 1000.0f + textMovin.getX());
textMovin.setY(speedY * period / 1000.0f + textMovin.getY());
if (textMovin.getY() <= 0 || textMovin.getY() >= height)
speedY *= -1;
if (textMovin.getX() <= 0 || textMovin.getX() >= width)
speedX *= -1;
}
});
}
}, 50, period);
}
});
findViewById(R.id.random).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random r = new Random();
speedX = r.nextFloat() * 200;
speedY = r.nextFloat() * 200;
}
});
}
}
and the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!" />
<Button
android:id="#+id/random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="Random" />
</RelativeLayout>
Hope it works for you.
public class OnDragTouchListener implements View.OnTouchListener {
/**
* Callback used to indicate when the drag is finished
*/
public interface OnDragActionListener {
/**
* Called when drag event is started
*
* #param view The view dragged
*/
void onDragStart(View view);
/**
* Called when drag event is completed
*
* #param view The view dragged
*/
void onDragEnd(View view);
}
private View mView;
private View mParent;
private boolean isDragging;
private boolean isInitialized = false;
private int width;
private float xWhenAttached;
private float maxLeft;
private float maxRight;
private float dX;
private int height;
private float yWhenAttached;
private float maxTop;
private float maxBottom;
private float dY;
private OnDragActionListener mOnDragActionListener;
public OnDragTouchListener(View view) {
this(view, (View) view.getParent(), null);
}
public OnDragTouchListener(View view, View parent) {
this(view, parent, null);
}
public OnDragTouchListener(View view, OnDragActionListener onDragActionListener) {
this(view, (View) view.getParent(), onDragActionListener);
}
public OnDragTouchListener(View view, View parent, OnDragActionListener onDragActionListener) {
initListener(view, parent);
setOnDragActionListener(onDragActionListener);
}
public void setOnDragActionListener(OnDragActionListener onDragActionListener) {
mOnDragActionListener = onDragActionListener;
}
public void initListener(View view, View parent) {
mView = view;
mParent = parent;
isDragging = false;
isInitialized = false;
}
public void updateBounds() {
updateViewBounds();
updateParentBounds();
isInitialized = true;
}
public void updateViewBounds() {
width = mView.getWidth();
xWhenAttached = mView.getX();
dX = 0;
height = mView.getHeight();
yWhenAttached = mView.getY();
dY = 0;
}
public void updateParentBounds() {
maxLeft = 0;
maxRight = maxLeft + mParent.getWidth();
maxTop = 0;
maxBottom = maxTop + mParent.getHeight();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isDragging) {
float[] bounds = new float[4];
// LEFT
bounds[0] = event.getRawX() + dX;
if (bounds[0] < maxLeft) {
bounds[0] = maxLeft;
}
// RIGHT
bounds[2] = bounds[0] + width;
if (bounds[2] > maxRight) {
bounds[2] = maxRight;
bounds[0] = bounds[2] - width;
}
// TOP
bounds[1] = event.getRawY() + dY;
if (bounds[1] < maxTop) {
bounds[1] = maxTop;
}
// BOTTOM
bounds[3] = bounds[1] + height;
if (bounds[3] > maxBottom) {
bounds[3] = maxBottom;
bounds[1] = bounds[3] - height;
}
switch (event.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
onDragFinish();
break;
case MotionEvent.ACTION_MOVE:
mView.animate().x(bounds[0]).y(bounds[1]).setDuration(0).start();
break;
}
return true;
} else {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDragging = true;
if (!isInitialized) {
updateBounds();
}
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragStart(mView);
}
return true;
}
}
return false;
}
private void onDragFinish() {
if (mOnDragActionListener != null) {
mOnDragActionListener.onDragEnd(mView);
}
dX = 0;
dY = 0;
isDragging = false;
}
}
And you can set it using:
myView.setOnTouchListener(new OnDragTouchListener(myView));
Or by adding this directly in init method of your Custom View:
setOnTouchListener(new OnDragTouchListener(this));

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.

Adding natural dragging effect to ImageView same as Facebook Messanger chat heads using Rebound library

I am developing one app where I am dragging around my ImageView in Activity.
I have configured Facebook Rebound library for spring animation which is originally used in Facebook Messenger's chat heads animations. I want to add this kind of animations to my ImageView when I drag it.
VIDEO
So far I am able to get spring animation when I touch ImageView (implemented spring on rootview), this is my code. How can I implement that natural type of dragging effect to my ImageView.
public class MainTry extends Activity {
int windowwidth;
int windowheight;
private LayoutParams layoutParams;
private final BaseSpringSystem mSpringSystem = SpringSystem.create();
private FrameLayout mRootView;
private Spring spring;
private View mImageView;
private VelocityTracker velocity = null;
private float dx;
private float dy;
private View rootView;
private ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
// Create a system to run the physics loop for a set of springs.
SpringSystem springSystem = SpringSystem.create();
// Add a spring to the system.
spring = springSystem.createSpring();
rootView = getWindow().getDecorView()
.findViewById(android.R.id.content);
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();
img = (ImageView) findViewById(R.id.imageView2);
rootView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// spring.setEndValue(1);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// spring.setEndValue(0);
break;
}
return true;
}
});
// Add a listener to observe the motion of the spring.
spring.addListener(new SimpleSpringListener() {
#Override
public void onSpringUpdate(Spring spring) {
// You can observe the updates in the spring
// state by asking its current value in onSpringUpdate.
float value = (float) spring.getCurrentValue();
float scale = .5f - (value * 0.1f);
img.setScaleX(scale);
img.setScaleY(scale);
}
});
// spring.setEndValue(1);
img.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) img
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dx = event.getRawX() - 10;
dy = event.getRawY() - 10;
if (velocity == null) {
// Retrieve a new VelocityTracker object to watch the
// velocity of a motion.
velocity = VelocityTracker.obtain();
} else {
// Reset the velocity tracker back to its initial state.
velocity.clear();
}
break;
case MotionEvent.ACTION_MOVE:
dx = event.getRawX() - 10;
dy = event.getRawY() - 10;
velocity.addMovement(event);
spring.setVelocity(velocity.getYVelocity());
spring.setCurrentValue(dy);
spring.setEndValue(dy);
layoutParams.leftMargin = (int) dx - 10;
layoutParams.topMargin = (int) dy - 10;
img.setLayoutParams(layoutParams);
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
velocity.addMovement(event);
spring.setVelocity(velocity.getYVelocity());
spring.setCurrentValue(event.getRawY() - 10);
spring.setEndValue(0);
break;
default:
break;
}
return true;
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
}
what about this:
class V extends View implements SpringListener {
private static final int NUM_ELEMS = 4;
private Spring[] mXSprings = new Spring[NUM_ELEMS];
private Spring[] mYSprings = new Spring[NUM_ELEMS];
private Paint mPaint = new Paint();
private Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
public V(Context context) {
super(context);
SpringSystem ss = SpringSystem.create();
Spring s;
for (int i = 0; i < NUM_ELEMS; i++) {
s = ss.createSpring();
s.setSpringConfig(new MySpringConfig(200, i == 0? 8 : 15 + i * 2, i, true));
s.addListener(this);
mXSprings[i] = s;
s = ss.createSpring();
s.setSpringConfig(new MySpringConfig(200, i == 0? 8 : 15 + i * 2, i, false));
s.addListener(this);
mYSprings[i] = s;
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mXSprings[0].setCurrentValue(w / 2);
mYSprings[0].setCurrentValue(0);
mXSprings[0].setEndValue(w / 2);
mYSprings[0].setEndValue(h / 2);
}
#Override
public void onSpringActivate(Spring s) {
}
#Override
public void onSpringAtRest(Spring s) {
}
#Override
public void onSpringEndStateChange(Spring s) {
}
#Override
public void onSpringUpdate(Spring s) {
MySpringConfig cfg = (MySpringConfig) s.getSpringConfig();
if (cfg.index < NUM_ELEMS - 1) {
Spring[] springs = cfg.horizontal? mXSprings : mYSprings;
springs[cfg.index + 1].setEndValue(s.getCurrentValue());
}
if (cfg.index == 0) {
invalidate();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mXSprings[0].setEndValue(event.getX());
mYSprings[0].setEndValue(event.getY());
return true;
}
#Override
protected void onDraw(Canvas canvas) {
for (int i = NUM_ELEMS - 1; i >= 0; i--) {
mPaint.setAlpha(i == 0? 255 : 192 - i * 128 / NUM_ELEMS);
canvas.drawBitmap(mBitmap,
(float) mXSprings[i].getCurrentValue() - mBitmap.getWidth() / 2,
(float) mYSprings[i].getCurrentValue() - mBitmap.getHeight() / 2,
mPaint);
}
}
class MySpringConfig extends SpringConfig {
int index;
boolean horizontal;
public MySpringConfig(double tension, double friction, int index, boolean horizontal) {
super(tension, friction);
this.index = index;
this.horizontal = horizontal;
}
}
}
i have used above V class directly in Window-manager and it's work perfectly and chatHead move like facebook messenger.
public class ChatHeadService extends Service
{
private LayoutInflater inflater;
private WindowManager windowManager;
private Point szWindow = new Point();
#Override
public void onCreate()
{
super.onCreate();
Log.v(Utils.LogTag, "Start Service");
}
private
void handleStart(){
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if (Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB) {
windowManager . getDefaultDisplay() . getSize(szWindow);
} else {
int w = windowManager . getDefaultDisplay() . getWidth();
int h = windowManager . getDefaultDisplay() . getHeight();
szWindow . set(w, h);
}
WindowManager . LayoutParams params = new WindowManager . LayoutParams(
WindowManager . LayoutParams . WRAP_CONTENT,
WindowManager . LayoutParams . WRAP_CONTENT,
WindowManager . LayoutParams . TYPE_PHONE,
WindowManager . LayoutParams . FLAG_NOT_FOCUSABLE |
WindowManager . LayoutParams . FLAG_WATCH_OUTSIDE_TOUCH |
WindowManager . LayoutParams . FLAG_LAYOUT_NO_LIMITS,
PixelFormat . TRANSLUCENT
);
params . gravity = Gravity . TOP | Gravity . LEFT;
params . x = 50;
params . y = 100;
V vImg = new V(this);
windowManager . addView(vImg, params);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
if (startId == Service . START_STICKY) {
handleStart();
}
}
return super . onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy(){
super . onDestroy();
if (windowManager != null) {
// windowManager.removeView(chatHeadView);
}
}
}

How to get child view with id from a viewgroup onclicklistener?

I am creating a floor map with n number of dynamic buttons with incremental value and added to a custom relative layout. Now i need to create onclicklistner for each buttons added to a view. How to get the id or some unique value to identify which button is clicked. Can somebody please help me on this i am breaking my head for the past 10 days. Thanks in advance.
This is my Custom Relative layout :
public class InteractiveView extends RelativeLayout implements OnClickListener{
Matrix matrix = new Matrix();
private float mPositionX = 0;
private float mPositionY = 0;
private float mScale = 0.1f;
private Context context;
private boolean canvasFlag = true;
public InteractiveView(Context context) {
super(context);
this.context = context;
this.setWillNotDraw(false);
// this.setOnTouchListener(mTouchListener);
this.setOnClickListener(this);
}
public void setPosition(float lPositionX, float lPositionY){
mPositionX = lPositionX;
mPositionY = lPositionY;
}
public void setMovingPosition(float lPositionX, float lPositionY){
mPositionX += lPositionX;
mPositionY += lPositionY;
}
public void setScale(float lScale){
mScale = lScale;
}
protected void dispatchDraw(Canvas canvas) {
canvas.save();
// canvas.setMatrix(matrix);
Log.e("Canvas Height ",canvas.getWidth()+" "+canvas.getHeight());
Log.e("Canvas Height ",getWidth() /14 +" "+getHeight()/12 );
Log.e("Canvas Density "," "+canvas.getDensity() );
canvas.translate(mPositionX*mScale, mPositionY*mScale);
canvas.translate(getWidth() / 14,getHeight() / 12);
if (mScale < 0.10)
mScale = 0.1f;
canvas.scale(mScale, mScale);
Log.e("Scale : ",mScale+" ");
super.dispatchDraw(canvas);
canvas.restore();
}
// touch events
private final int NONE = 0;
private final int DRAG = 1;
private final int ZOOM = 2;
private final int CLICK = 3;
// pinch to zoom
private float mOldDist;
private float mNewDist;
private float mScaleFactor = 0.01f;
// position
private float mPreviousX;
private float mPreviousY;
int mode = NONE;
#SuppressWarnings("deprecation")
public OnTouchListener mTouchListener = new OnTouchListener(){
public boolean onTouch(View v, MotionEvent e) {
/*Button button = (Button)v;
Log.e("Button Text : "," "+button.getText().toString());
*/
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN: // one touch: drag
mode = CLICK;
break;
case MotionEvent.ACTION_POINTER_2_DOWN: // two touches: zoom
mOldDist = spacing(e);
mode = ZOOM; // zoom
break;
case MotionEvent.ACTION_UP: // no mode
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_2_UP: // no mode
mode = NONE;
break;
case MotionEvent.ACTION_MOVE: // rotation
if (e.getPointerCount() > 1 && mode == ZOOM) {
/*mNewDist = spacing(e) - mOldDist;
mScale += mNewDist*mScaleFactor;
invalidate();
mOldDist = spacing(e); */
} else if (mode == CLICK || mode == DRAG) {
float dx = (x - mPreviousX)/mScale;
float dy = (y - mPreviousY)/mScale;
setMovingPosition(dx, dy);
invalidate();
mode = DRAG;
}
break;
}
mPreviousX = x;
mPreviousY = y;
return true;
}
};
// finds spacing
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y)/4;
}
This is my fragment class where i create floor map :
public class FloorMapFragment extends Fragment implements OnClickListener {
ViewGroup root;
Button exhibitor;
ZoomControls zoom;
int id = 0;
float dx=0,dy=0,x=0,y=0;
InteractiveView mInteractiveView;
int startX, startY;
boolean isClicked = false;
int unit = 100;
int incremental = 100;
int new_X;
int i;
int new_Width = new_X + incremental;
int new_Y;
int new_Hight = new_Y + incremental;
int leftMargin, topMargin;
int orange = Color.parseColor("#C0680F");
int maroon = Color.parseColor("#5F0C0C");
int pink = Color.parseColor("#F45C91");
int moov = Color.parseColor("#6E4689");
int gray = Color.parseColor("#777777");
int red = Color.parseColor("#E31E26");
int blue = Color.parseColor("#3A53A4");
int green = Color.parseColor("#70BD59");
int cyan = Color.parseColor("#70CDDD");
RelativeLayout r;
// View mainView = null;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
PointF oldDistPoint = new PointF();
public static String TAG = "ZOOM";
int mScreenWidth = 0;
int mScreenHeight= 0;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
enum Direction {
LEFT, RIGHT, UP, DOWN
};
FloorListner listner;
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = (ViewGroup) inflater.inflate(R.layout.floor_main, null);
// mainView = (RelativeLayout)root.findViewById(R.id.zoom_layout);
r = (RelativeLayout) root.findViewById(R.id.my_relative_layout);
zoom = (ZoomControls)root. findViewById(R.id.zoomControls1);
mScreenWidth = r.getWidth();
/*MainActivity.activity.getResources()
.getDisplayMetrics().widthPixels;*/
mScreenHeight = r.getHeight();
/*MainActivity.activity.getResources()
.getDisplayMetrics().heightPixels; */
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
layoutParams.height = 75;
layoutParams.width = 57;
// layoutParams.bottomMargin = 100;
// layoutParams.setMargins(0, 0, 0, 100);
// layoutParams.setMargins(-220, 0, 0, 0);
/*ImageView lImageView = new ImageView(MainActivity.activity);
lImageView.setLayoutParams(new RelativeLayout.LayoutParams(-1,-1));
lImageView.setImageResource(R.drawable.transparentimage);;*/
mInteractiveView = new InteractiveView(MainActivity.activity);
// mInteractiveView.setOnClickListener(this);
// mInteractiveView.setOnTouchListener(mTouchListener);
// mInteractiveView.setLayoutParams(new RelativeLayout.LayoutParams(-5,-5 ));
// mInteractiveView.setLayoutParams(layoutParams);
// mInteractiveView.setPosition(-mScreenWidth/2, -mScreenHeight/2);
zoom.setOnZoomInClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
float x = r.getScaleX();
float y = r.getScaleY();
Log.e("Zoon In Listener : ", "X Scale : "+ x );
Log.e("Zoon In Listener : ", "Y Scale : "+ y );
Log.e("Zoon In Width : ", "X Scale : "+ r.getWidth() );
Log.e("Zoon In Height : ", "Y Scale : "+ r.getHeight() );
if (x <= 6.0 && y <= 6.0){
r.setScaleX((float) (x + 0.5));
r.setScaleY((float) (y + 0.5));
}
}
});
zoom.setOnZoomOutClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
float x = r.getScaleX();
float y = r.getScaleY();
Log.e("Zoon Out Listener : ", "X Scale : "+ x );
Log.e("Zoon Out Listener : ", "Y Scale : "+ y );
if (x > 1.0 && y > 1.0){
r.setScaleX((float) (x - 0.5));
r.setScaleY((float) (y - 0.5));
}
}
});
ProgressDialog d = new ProgressDialog(getActivity());
d.setMessage("Loading Map");
d.show();
draw();
d.dismiss();
/*
mInteractiveView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});*/
/*for( i=0; i<((ViewGroup)mInteractiveView).getChildCount(); ++i) {
View nextChild = ((ViewGroup)mInteractiveView).getChildAt(i);
try {
final Button b = (Button) nextChild;
Log.e("Button Text : ", " : "+b.getText().toString());
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = ((ViewGroup)b.getParent()).indexOfChild(b);
Log.e("Button get Id : ", ""+v.getTag().toString());
}
});
} catch (Exception e) {
}
}*/
//
// mInteractiveView.addView(lImageView);
// r.setLayoutParams(layoutParams);
r.addView(mInteractiveView);
/* ExhibitorDAO dao = new ExhibitorDAO(getActivity());
workAround(dao, "K19");*/
/* Fragment fragment = new NewsFragment();
FragmentTransaction trans = ;
trans.addToBackStack(null);
trans.replace(R.id.main, fragment);
trans.commit();*/
// r.setOnTouchListener(MyOnTouchListener);
// r.setLayoutParams(layoutParams);
Log.e("Width And Height : ", "Width : "+r.getLayoutParams().width+ " : Height :"+r.getLayoutParams().height);
return root;
}
private OnTouchListener mTouchListener = new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
isClicked = true;
x = event.getX();
y = event.getY();
dx = x-r.getX();
dy = y-r.getY();
break;
case MotionEvent.ACTION_UP:
if (isClicked){
isClicked = false;
/*Button b = (Button) v;
ExhibitorDAO dao = new ExhibitorDAO(getActivity());
workAround(dao,b.getText().toString());*/
}
break;
case MotionEvent.ACTION_POINTER_UP:
isClicked = false;
break;
case MotionEvent.ACTION_POINTER_DOWN:
isClicked = false;
break;
case MotionEvent.ACTION_MOVE:
r.setX(event.getX()-dx);
r.setY(event.getY()-dy);
isClicked = false;
break;
default:
break;
}
return false;
}
};
private void decreaseXBy(int i) {
new_X = new_X - (2 * i);
}
private void reset() {
new_X = 0;
new_Y += incremental;
;
}
private void drawingH(Direction direction, float width) {
if (direction == direction.RIGHT) {// means go to right direction{
new_X += (incremental * width);
} else if (direction == direction.LEFT) { // means go to left
new_X -= (incremental * width);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button b = (Button) v;
ExhibitorDAO dao = new ExhibitorDAO(getActivity());
try{
Exhibitor exhibitor = new Exhibitor();
Log.e("Button Text : ", " : "+b.getText());
if (!b.getText().equals("")) {
Logger.log("floor:");
exhibitor = dao.getExhibitorByBooth(b.getText().toString());
ExhibitorApplication ex = new ExhibitorApplication();
ex.exhibitor = exhibitor;
if (exhibitor != null){
listner.Onfloorclick();
ex.fav_exhibitor = 4 ;
Logger.log("floor:"+ex.exhibitor.Exhibitor_FileNumber);
}
else
{
Logger.log("floor:"+ex.exhibitor.Exhibitor_FileNumber);
}
}
{
Logger.log("floor:no data");
}
}
catch(Exception ex)
{
Toast.makeText(getActivity(), "No Information "+ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public Button drawExhibitor(float width, int height, int color,
String label, String fileNumber, Direction d) {
exhibitor = new Button(getActivity());
// exhibitor.setOnClickListener(this);
// exhibitor.setOnTouchListener(MyOnTouchListener);
if (color == Color.BLUE)
exhibitor.setBackgroundColor(Color.parseColor("#56A5EC"));
if (color == Color.WHITE)
exhibitor.setAlpha(0);
else
exhibitor.setBackgroundColor(color);
// exhibitor.setId(id);
// id++;
exhibitor.setText(label);
exhibitor.setTextSize(8);
// exhibitor.setId(foo);
exhibitor.setTag(label);
exhibitor.setTypeface(Typeface.DEFAULT_BOLD);
exhibitor.setGravity(Gravity.CENTER);
exhibitor.setTextColor(Color.WHITE);
/*exhibitor.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Button get Id : ", ""+exhibitor.getId());
}
});*/
exhibitor.setOnTouchListener(mTouchListener);
leftMargin = new_X;
topMargin = new_Y;
drawingH(d, width);
InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
(int) (width * incremental), height * incremental);
params.leftMargin = leftMargin;
params.topMargin = topMargin;
mInteractiveView.addView(exhibitor, params);
params = null;
if (color != Color.WHITE) {
drawingHSpace();
}
return exhibitor;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof FloorListner) {
listner = (FloorListner) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.OnItemSelectedListener");
}
}
private void drawingHSpace() {
new_X += 2;
}
private void drawingHSpace(float t) {
new_X = (int) (new_X + (2 * t));
}
private void drawingVSpace() {
new_Y += 2;
}
private void removeDrawingVSpace() {
new_Y -= 2;
}
private void decreaseXBy(float i) {
new_X = (int) (new_X - (2 * i));
}
private void drawLabel(float width, int height, int color, int drawable, Direction d) {
// TODO Auto-generated method stub
TextView image = new TextView(getActivity());
//image.setText(label);
image.setBackgroundResource(drawable);
image.setGravity(Gravity.CENTER);
image.setTextSize(20);
image.setTypeface(Typeface.DEFAULT_BOLD);
//image.setTextColor(color);
// image.setOnTouchListener(MyOnTouchListener);
leftMargin = new_X;
topMargin = new_Y;
drawingH(d,width);
InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
(int)(width * incremental), height * incremental);
params.leftMargin = leftMargin;
params.topMargin = topMargin;
mInteractiveView.addView(image, params);
}
private void drawLabel(float width, int height, int color, String label, Direction d) {
// TODO Auto-generated method stub
TextView image = new TextView(getActivity());
image.setText(label);
image.setGravity(Gravity.CENTER);
image.setTextSize(20);
image.setTypeface(Typeface.DEFAULT_BOLD);
image.setTextColor(color);
// image.setOnTouchListener(mTouchListener);
leftMargin = new_X;
topMargin = new_Y;
drawingH(d,width);
InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
(int)(width * incremental), height * incremental);
params.leftMargin = leftMargin;
params.topMargin = topMargin;
mInteractiveView.addView(image, params);
}
private void draw() {
drawExhibitor(28.5F, 3, Color.WHITE, "", "", Direction.RIGHT);
drawLabel(2, 3, blue, R.drawable.al_mamzar, Direction.RIGHT);
reset();
reset();
drawExhibitor(16.5F, 1, Color.WHITE, "", "", Direction.RIGHT);
drawLabel(2, 1, blue, R.drawable.business_center, Direction.RIGHT);
drawExhibitor(4.65F, 1, Color.WHITE, "", "", Direction.RIGHT);
drawLabel(1, 1, blue, R.drawable.bath_f, Direction.RIGHT);
drawExhibitor(14F, 1, Color.WHITE, "", "", Direction.RIGHT);
drawLabel(1, 1, blue, R.drawable.bath_m, Direction.RIGHT);
//reset();
reset();
drawingVSpace();
drawingVSpace();
}
}
Finally i am adding the Interactive View to a relative layout.
As you will find it in the documentation that each view can have an id (using setId (int id) or from xml android:id ) or tag(using setTag (int key)) associated with it and later on you can get that id or tag via getId() or getTag().
Now before you actually retrieve any id for a view at first you have to set an id for that specific view either via programmatically or via xml.
If you don't specify any id for a view and you are trying get that view's id you will get NO_ID.
As per documentation: getId () returns this view's identifier.A positive integer used to identify the view or NO_ID if the view has no ID.
Now to address your problem, before you add a button to your viewgroup assign a unique id to that button.
To illustrate more here is an example:
public class MainActivity extends Activity {
private LinearLayout mRootLayout;
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.e("mButton "," onClick");
Toast.makeText(MainActivity.this, " "+arg0.getId(), Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRootLayout = (LinearLayout)findViewById(R.id.mRootLayout);
for(int i = 0;i<10;i++){
Button mButton = new Button(this);
mButton.setText("Button "+i);
mButton.setId(i);
if(i<9){
mButton.setOnClickListener(mOnClickListener);
}
mRootLayout.addView(mButton);
}
Button testFindButton = (Button)mRootLayout.findViewById(9);
testFindButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("testFindButton "," onClick");
Toast.makeText(MainActivity.this, " testFindButton "+v.getId(), Toast.LENGTH_LONG).show();
}
});
}
}
You can use the setTag method for each button, to set an id. Then in the onClick method, retrieve that value, and execute the code related to that button.
Some code (not tested):
private OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v)
{
int id = (Integer)v.getTag();
switch (id)
{
case 1: break;
....
}
}
});
for (int i=0 ; i<N ; i++)
{
yourbutton.setTag(Integer.valueOf(i));
yourbutton.setOnClickListener(listener);
}

Android with SeekBar - Prevent 'thumb' from moving when touching SeekBar to drag/scroll screen

I've got an android app with a TableLayout with each row having a SeekBar and a ToggleButton. The rows go beyond the visible range of the screen so it's scrollable. When I touch and drag to scroll the page up and in the process touch the SeekBar, it immediately changes the position of the "thumb" instead of scrolling the page. However, the ToggleButton does not behave this way; instead, I can start the drag on the button and scroll then release without the ToggleButton changing state.
Is there anyway to get the SeekBar to behave this way, such that touching it to start a drag will not cause the bar to change positions but instead scroll the page?
I've had similar problems. The only solution I could find (when the seekbar is in a listview) was to disable the seekbar until the item is clicked.
Solution
In the ArrayAdapter I set both enabled and focusable to false and added the SeekBar listener, setting the attributes to false allowed me to use the list item onItemClicked listener. Inside the onItemCLickListener I retreived the seekbar, set the attributes to true, this meant it could be slid up or down. I then disabled it after the adjustment had been made. code below
ArrayAdapter Snippet
this code is inside the creation of the list item, in which the seekbar is housed
seekBar.setClickable(false);
seekBar.setFocusable(false);
seekBar.setEnabled(false);
/* attach listener */
attachProgressUpdatedListener(seekBar, positionOfItemInList);
AttachProgressUpdatedListener
this method attaches the listener to the seekbar, inside the arrayAdapter class
private void attachProgressUpdatedListener(SeekBar seekBar,
final int position) {
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
int task_id = (Integer) seekBar.getTag();
TaskHandler taskHandler = new TaskHandler(DBAdapter
.getDBAdapterInstance(getContext()));
taskHandler.updateTaskProgress(task_id, progress);
mList.get(position).setProgress(progress);
//need to fire an update to the activity
notifyDataSetChanged();
seekBar.setEnabled(false);
}
public void onStartTrackingTouch(SeekBar seekBar) {
// empty as onStartTrackingTouch listener not being used in
// current implementation
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// empty as onProgressChanged listener not being used in
// current implementation
}
});
}
OnItemCLickListener
this snipped is from the activity which houses the list view.
taskListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SeekBar sb = (SeekBar) view.findViewById(R.id.seek);
sb.setFocusable(true);
sb.setEnabled(true);
}
});
I got it working by subclassing the seekbar and checking if the angle of motion is greater than 45 degrees. In that case ignore touches and return false so scroll view will do its thing.
Edit:
Here is an extended SeekBar which allows you to set a min/max in floats rather than integers.
public class SeekBarEx extends SeekBar implements
SeekBar.OnSeekBarChangeListener {
final int SEEK_POINTS = 0x10000;
final String TAG = "SeekBarEx";
public float mMax;
public float mMin;
public OnSeekBarExChangeListener delegate = null;
public interface OnSeekBarExChangeListener {
public void onSeekChanged(SeekBarEx seekBarEx, float value,
boolean fromUser);
public void onStartTrackingTouch(SeekBarEx seekBar);
public void onStopTrackingTouch(SeekBarEx seekBar);
}
public SeekBarEx(Context ctx, AttributeSet attr) {
super(ctx, attr);
super.setMax(SEEK_POINTS);
mMin = 0f;
mMax = 1.0f;
initAttributes(attr);
this.setOnSeekBarChangeListener(this);
}
public void setDelegate(OnSeekBarExChangeListener d) {
delegate = d;
}
public void initAttributes(AttributeSet attrSet) {
TypedArray a;
a = getContext().obtainStyledAttributes(attrSet, R.styleable.SeekBarEx);
final int N = a.getIndexCount();
int i;
for (i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.SeekBarEx_max:
mMax = a.getFloat(i, 1.0f);
Log.d(TAG, "maxSet " + mMax);
break;
case R.styleable.SeekBarEx_min:
mMin = a.getFloat(i, 0f);
Log.d(TAG, "minSet" + mMin);
break;
case R.styleable.SeekBarEx_value:
this.setValue(a.getFloat(i, 0));
break;
}
}
a.recycle();
}
#Override
public int getProgress() {
return super.getProgress();
}
public float getValue() {
float r;
float run;
r = (float) super.getProgress();
r = r / (float) SEEK_POINTS;
run = mMax - mMin;
r = r * run + mMin;
return r;
}
public void setValue(float v) {
if (Float.isNaN(v) || Float.isInfinite(v))
return;
if (v > mMax)
v = mMax;
if (v < mMin)
v = mMin;
float run;
int setv;
run = mMax - mMin;
v -= mMin;
setv = Math.round(v * (float) SEEK_POINTS / run);
super.setProgress(setv);
}
public boolean valueChanged = false;
public void cancelTracking() {
if (oldValue != Float.NaN) {
this.setValue(oldValue);
oldValue = Float.NaN;
valueChanged = false;
acceptTouches = false;
acceptChange = false;
}
}
// we override these methods so that when we forcully cancel
// on ontouches moved. We can revert back to the old value
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Log.d(TAG, "SeekBar changed to " + progress);
if (delegate != null && acceptTouches) {
valueChanged = true;
delegate.onSeekChanged(this, this.getValue(), fromUser);
} else
cancelTracking();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (delegate != null)
delegate.onStartTrackingTouch(this);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (delegate != null && valueChanged)
delegate.onStopTrackingTouch(this);
else
cancelTracking();
acceptChange = false;
valueChanged = false;
}
public float mY, mX;
public boolean acceptTouches = true;
// acceptChange never read todo: delete
public boolean acceptChange = false;
public float oldValue = Float.NaN;
public ScrollView getScrollView() {
View view;
view = this;
int maxUp;
maxUp = 5;
while (view != null && maxUp > 0) {
view = (View) view.getParent();
ScrollView scroller;
if (view instanceof ScrollView) {
scroller = (ScrollView) view;
return scroller;
}
maxUp--;
}
return null;
}
// **************************************
// This is the important part in achieving the effect in scroll
// view to be nice
#Override
public boolean onTouchEvent(MotionEvent event) {
int action;
action = event.getAction() & MotionEvent.ACTION_MASK;
ScrollView scroller = this.getScrollView();
boolean mayScroll;
mayScroll = true;
if (scroller == null)
mayScroll = false;
else {
int scrollAmount = scroller.getMaxScrollAmount();
if (scrollAmount == 0)
mayScroll = false;
}
switch (action) {
case MotionEvent.ACTION_CANCEL:
Log.d(TAG, "got cancel touches");
cancelTracking();
super.onTouchEvent(event);
return true;
case MotionEvent.ACTION_DOWN:
mX = event.getX();
mY = event.getY();
acceptTouches = true;
acceptChange = false;
oldValue = this.getValue();
valueChanged = false;
break;
case MotionEvent.ACTION_MOVE:
float x;
float y;
x = event.getX();
y = event.getY();
float dx;
float dy;
dx = x - mX;
dy = y - mY;
if (dx < 0)
dx = -dx;
if (dy < 0)
dy = -dy;
y = this.getHeight() / 2 - y;
float angle;
float distance;
distance = dx * dx + dy * dy;
// I just realized this is wrong it should be
// angle = (float)Math.acos(Math.abs(dx)/Math.sqrt(distance))
// I'm leaving it until tested or someone can confirm
angle = (float) Math.atan(dy / dx);
int distanceLimit;
distanceLimit = this.getHeight() / 3;
distanceLimit *= distanceLimit;
// if we move at an angle of atleast 45degrees
// cancel
if (mayScroll && angle > Math.PI / 4.0) {
cancelTracking();
}
mX += 100000;
if (y < 0)
y = -y;
// if we moved finger too far just cancel
// cause the person may have wanted to scroll but
// failed so we revert back to the old value
if (y > this.getHeight() * 2) {
cancelTracking();
} else if (acceptTouches)
acceptChange = true;
break;
default:
break;
}
// if we accept touches do the usual otherwise
// return false so scrollView can do it's thing
if (acceptTouches)
return super.onTouchEvent(event);
return false;
}
}
seekbarex.xml is bellow. This is just to add min/max/value as floats.
<declare-styleable name="SeekBarEx">
<attr name="min" format="float"/>
<attr name="max" format="float"/>
<attr name="value" format="float"/>
</declare-styleable>
</resources>

Categories

Resources