(Android) Making Images Visible/Not Visible when touched - android

This is my updated code. It doesn't detect movement at all now. Maybe I shouldn't be making each Image an instance? Basically I want to user to be able to swipe through all the images to make them dissapear.
Thanks for all the help.
package com.picomputing.mythirdapplication;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
/**
* Created by Paul on 8/13/13.
*/
public class Pin extends ImageView implements View.OnTouchListener {
boolean isPinDown;
public Pin(Context context) {
super(context);
this.isPinDown = false;
}
public Pin(Context context, AttributeSet attrs) {
super(context, attrs);
this.isPinDown = false;
}
public Pin(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.isPinDown = false;
}
public boolean pinDown() {
return this.isPinDown;
}
public void setPinDown() {
this.isPinDown = true;
}
public void setPinUp() {
this.isPinDown = false;
}
public void togglePin() {
if (isPinDown == false)
{
isPinDown = true;
this.setImageResource(Color.TRANSPARENT);
}
else
{
isPinDown = false;
this.setImageResource(R.drawable.pin);
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX(); //--relative to mLayout--
int y = (int) event.getY(); //--relative to mLayout--
Rect r = new Rect();
view.getHitRect(r);
if(r.contains(x,y) && view instanceof ImageView){
togglePin();
}
}
return true;
}
}

You need to listen and consume ACTION_MOVE events, for the parent view of whatever you are trying to change.
Here's an example with a couple of ImageViews in a LinerLayout as a parent:
public class test extends Activity {
LinearLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = new LinearLayout(this);
mLayout.setOrientation(LinearLayout.VERTICAL);
for(int i = 0 ; i < 5; i++){
ImageView iv = new ImageView(this);
iv.setImageResource(android.R.drawable.ic_dialog_info);
mLayout.addView(iv);
}
setContentView(mLayout);
mLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX(); //--relative to mLayout--
int y = (int) event.getY(); //--relative to mLayout--
Rect r = new Rect();
for(int i = 0 ; i < mLayout.getChildCount(); i++){
View v = mLayout.getChildAt(i);
v.getHitRect(r);
if(r.contains(x,y) && v instanceof ImageView){
((ImageView) v).setImageResource(android.R.drawable.ic_dialog_alert);
}
}
}
return true; //-- this means that view is interested in more events of all kinds--
}
});
}
}

I hope I didn't misunderstand your question
but if what you want to do is to prevent multitoch on the image you can add this attribute
android:splitMotionEvents="false"
in the xml in the parent view of the imageview. for example :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:splitMotionEvents="false"
>
// YOUR IMAGE VIEW HERE
</LinearLayout>
if you have any question feel free to ask in the comment :)

there are mainly three events on OnTouch action_down,Action_move and Action_up. do your coding on action down event i.e when user has touched your view. see the example here:
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction()==MotionEvent.ACTION_DOWN) {
//write your code here
}
else {
if (arg1.getAction()==MotionEvent.ACTION_MOVE){
do things
}
else {
if (arg1.getAction()==MotionEvent.ACTION_UP){
do things
}
}
}

Related

OnLongClickListener not working in custom framelayout Android

I have an ImageView in a FrameLayout, I want to setup LongClickListener but its failing to work, I tried setting up OnTouchListener and its working flawless, I do not have the slightest idea as to why its not working but below is my code code:
public class DragImageView extends FrameLayout implements View.OnLongClickListener {
ImageView ivDrag;
public DragImageView(Context context) {
super(context);
}
public DragImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DragImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void AddImageView(View draggableObject, int x, int y, int width, int height) {
LayoutParams lpDraggableView = new LayoutParams(width, height);
lpDraggableView.gravity = Gravity.TOP;
lpDraggableView.leftMargin = x;
lpDraggableView.topMargin = y;
if(draggableObject instanceof ImageView) {
this.ivDrag = (ImageView) draggableObject;
ivDrag.setLayoutParams(lpDraggableView);
ivDrag.setClickable(true);
ivDrag.setLongClickable(true);
ivDrag.setOnLongClickListener(this);
this.addView(ivDrag);
}
}
/**
* Draggable object ontouch listener
* Handle the movement of the object when dragged and dropped
*/
private View.OnTouchListener OnTouchToDrag =new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
FrameLayout.LayoutParams dragParam = (LayoutParams) v.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
dragParam.topMargin = (int)event.getRawY() - (v.getHeight());
dragParam.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(dragParam);
break;
}
case MotionEvent.ACTION_UP:
{
dragParam.height = v.getHeight();
dragParam.width = v.getWidth();
dragParam.topMargin = (int)event.getRawY() - (v.getHeight());
dragParam.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(dragParam);
break;
}
case MotionEvent.ACTION_DOWN:
{
dragParam.height = v.getHeight();//fixed on drag and drop
dragParam.width = v.getWidth();
v.setLayoutParams(dragParam);
break;
}
}
return true;
}
};
#Override
public boolean onLongClick(View view) {
ivDrag.setOnTouchListener(OnTouchToDrag);
Toast.makeText(view.getContext(), "OnLongClick", Toast.LENGTH_SHORT).show();
return false;
}
}
I want to setup LongClickListener but its failing to work
You are not receiving the callbacks from OnLongClickListener because it has no set listener. Since your class implements View.OnLongClickListener and you want to receive the callback in your overridden onLongClick() method, add this class itself as the listener and it will work. I've done so in the constructor (choose the appropriate constructor out of the three as per your initialization of the view):
public DragImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnLongClickListener(this); // <-- set this class instance as the listener
}
Although I'm surprised how you got it working with OnTouchListener. You probably explicitly added the listener, right?

Send Value to Main from extended View

I have this activity that detects Multi-Touch and counts each instance that the device is tapped over 3 times. What I want is to do a check in Main to see if it reaches the limit that have been set.
Main Activity
package com.test.multitouch;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// DETECT more than 20 counts here and display a toast
}
Custom View which extends view
package com.test.multitouch;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
#SuppressLint("ClickableViewAccessibility")
public class custom_view extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
final int MAX_NUMBER_OF_POINT = 4;
float[] x = new float[MAX_NUMBER_OF_POINT];
float[] y = new float[MAX_NUMBER_OF_POINT];
boolean[] touching = new boolean[MAX_NUMBER_OF_POINT];
int count = 0;
long cur = System.currentTimeMillis();
long dur = 30000;
long fut = cur + dur;
public custom_view(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public custom_view(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public custom_view(Context context) {
super(context);
init();
}
void init() {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(40);
}
#Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < MAX_NUMBER_OF_POINT; i++) {
if (touching[i]) {
switch (i) {
case 1:
paint.setColor(Color.BLUE);
break;
case 2:
paint.setColor(Color.RED);
break;
case 3:
paint.setColor(Color.YELLOW);
break;
case 4:
paint.setColor(Color.GREEN);
break;
}
canvas.drawCircle(x[i], y[i], 70f, paint);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = (event.getAction() & MotionEvent.ACTION_MASK);
int pointCount = event.getPointerCount();
if (pointCount > 3) {
Log.i("LOG", "register multi touch");
count++;
if (count > 20) {
//SEND BACK TO MAIN TO SAY IT HAS BEEN ACHIEVED
}
}
for (int i = 0; i < pointCount; i++) {
int id = event.getPointerId(i);
if (id < MAX_NUMBER_OF_POINT) {
x[id] = (int) event.getX(i);
y[id] = (int) event.getY(i);
if ((action == MotionEvent.ACTION_DOWN)
|| (action == MotionEvent.ACTION_POINTER_DOWN)
|| (action == MotionEvent.ACTION_MOVE)) {
touching[id] = true;
} else {
touching[id] = false;
}
}
}
invalidate();
return true;
}
}
Your custom view has a reference to the context it's attached to. I assume this view is running in the same activity you are trying to reference. You can get the reference to the activity as follows:
MainActivity mainActivity = (MainActivity) custom_view.this.getContext();
I also assumed you are calling this from inside your onTouchListener. You need to reference the "this" to get to the outterclass instance, otherwise this will refer to the instance of your onTouchListener class instead. Also, you should capitalize class names, so you can recognize from the capitalization whether we are referring to an instance or class definition.
Once you have the reference, you can call some function on main Activity to update it.
mainActivity.callSomeFunction();

Android: drag item out of scrolling list/gallery

I want to implement a Gallery that allows the user to drag items out of it. This shouldn't get in the way of scrolling/flinging.
Given the interface layout, the user can only drag items out of the Gallery in a vertical path, and scroll the Gallery horizontally.
Is this feasible? Is there an easy way of detecting horizontal movements, and defer them to the Gallery's event handlers, and intercept vertical movements? Or do I have to override onInterceptTouchEvent() and do the math myself?
(edit: I'm giving a try to a GestureListener, overriding onFling and onScroll, and passing the events to the Gallery when the vertical scroll distance is below a threshold)
I inherited Gallery, and overrode the onScroll method. I haven't implemented the drop logic yet, but the dragging and scrolling work.
When I can spare the time, I'll write a full post in my blog with more details, and the drop mechanism. For now, a simple copy-paste in case somebody reaches this page in the future.
To keep the behavior where it belongs, I created this DraggableView interface:
public interface DraggableView {
public void beforeDrag();
public DragView createDragView();
public Object getDraggedInfo();
public void afterDrop();
}
Views in the Gallery can be dragged out of the Gallery area if they implement this view. They are notified before and after, and must implement two methods:
createDragView() returns a DragView object. Basically, a transparent hovering bitmap to accompany the user's movement.
getDraggedInfo() returns the information that should reach the drop target.
Here's the DragView class:
public class DragView extends ImageView {
private final LayoutParams mLayoutParams;
public DragView(Context context, Bitmap bitmap) {
super(context);
mLayoutParams = new LayoutParams();
mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
mLayoutParams.height = LayoutParams.WRAP_CONTENT;
mLayoutParams.width = LayoutParams.WRAP_CONTENT;
mLayoutParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE
| LayoutParams.FLAG_NOT_TOUCHABLE;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.windowAnimations = 0;
mLayoutParams.alpha = 0.5f;
setImageBitmap(bitmap);
setLayoutParams(mLayoutParams);
}
public void move(int x, int y) {
mLayoutParams.x = x;
mLayoutParams.y = y;
}
}
As you can see, it takes a Bitmap in construction, and creates a hovering ImageView. Finally, here is the (just implemented and not very clean) Gallery code to make it all happen:
public class DraggableItemGallery extends Gallery {
private boolean mDragging;
private DragView mDragView;
private DraggableView mDragViewOwner;
private WindowManager mWindowManager;
private boolean mScrollStarted;
public DraggableItemGallery(Context context) {
super(context);
initialize();
}
public DraggableItemGallery(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public DraggableItemGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void initialize() {
mWindowManager = (WindowManager)
getContext().getSystemService("window");
}
private void startDraggingItem(DraggableView view, int x, int y) {
mDragging = true;
mDragViewOwner = view;
mDragView = view.createDragView();
mDragView.move(x, y);
mWindowManager.addView(mDragView, mDragView.getLayoutParams());
}
private void continueDraggingItem(int x, int y) {
DragView dragView = getDragView();
dragView.move(x, y);
mWindowManager.updateViewLayout(dragView, dragView.getLayoutParams());
}
private void stopDraggingItem() {
mDragging = false;
mWindowManager.removeView(mDragView);
mDragViewOwner.afterDrop();
mDragView = null;
mDragViewOwner = null;
}
private DraggableView getDraggedItem() {
return mDragViewOwner;
}
private DragView getDragView() {
return mDragView;
}
private boolean isDraggingItem() {
return (mDragging);
}
private void setScrolling(boolean scrolling) {
mScrollStarted = scrolling;
System.out.println("Scrolling " + scrolling);
}
private boolean isScrolling() {
return mScrollStarted;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if ((event.getAction() & ACTION_MASK) == ACTION_UP) {
setScrolling(false);
if (isDraggingItem())
stopDraggingItem();
}
return super.onTouchEvent(event);
}
final Rect onScroll_tempRect = new Rect();
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (isScrolling()) {
if (isDraggingItem()) {
int x = (int) e2.getX(),
y = (int) e2.getY();
System.out.println("Moving to " + x + " " + y);
continueDraggingItem(x, y);
return true;
} else {
/* Not dragging, let the Gallery handle the event */
return super.onScroll(e1, e2, distanceX, distanceY);
}
} else {
setScrolling(true);
boolean isVertical = (Math.abs(distanceY) > Math.abs(distanceX));
if (isVertical) {
int x = (int) e1.getX(),
y = (int) e1.getY();
View hitChild = null;
// A tiny optimization, declared above this method
final Rect hitRect = onScroll_tempRect;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.getHitRect(hitRect);
if (hitRect.contains(x, y)) {
hitChild = child;
break;
}
}
if (hitChild instanceof DraggableView) {
startDraggingItem((DraggableView) hitChild, x, y);
return true;
}
}
/* Either the scroll is not vertical, or the point
* of origin is not above a DraggableView. Again,
* we let the Gallery handle the event.
*/
return super.onScroll(e1, e2, distanceX, distanceY);
}
}
}
Hope it helps.
Here is something I did to do exactly that. That's only the code for the activity... there is some layout and other res files you'll need...
Every list item has an icon and name matched randomly.
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.FrameLayout.LayoutParams;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.Arrays;
public class DragActivity extends Activity implements View.OnTouchListener, AdapterView.OnItemLongClickListener
{
private static final String TAG="DragActivity";
private static final int NOT_DRAGGING = 0;
private static final int DRAGGING = 1;
private int state=NOT_DRAGGING;
private ImageView draggable =null;
private int dragged_position;
float current_x, current_y;
int current_icon = R.drawable.notepad;
private ArrayList<String> names = new ArrayList<String>(Arrays.asList("John", "Mark", "Mathew", "Luke", "Bob", "Will", "Brian", "Mike"));
private ArrayList<Integer> icons = new ArrayList<Integer>(Arrays.asList( R.drawable.glasses, R.drawable.monkey, R.drawable.normal, R.drawable.smile, R.drawable.wink));
private ArrayList<Integer> matching;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupListContent();
ListView list = (ListView) findViewById(R.id.main_list);
list.setAdapter(new DragListAdapter());
list.setOnItemLongClickListener(this);
list.setOnTouchListener(this);
// need to use the same view for the both listeners, as described in Android documentation :
// http://developer.android.com/guide/topics/ui/ui-events.html
// onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing
// is that this event can have multiple actions that follow each other. So, if you return false when the down action
// event is received, you indicate that you have not consumed the event and are also not interested in subsequent
// actions from this event. Thus, you will not be called for any other actions within the event, such as a finger
// gesture, or the eventual up action event.
ImageView image = (ImageView) findViewById(R.id.main_image);
image.setImageResource(current_icon);
}
private void setupListContent() {
matching = new ArrayList<Integer>();
for (int i=0; i<names.size(); i++) {
matching.add((int) (icons.size() * Math.random()));
}
}
#SuppressWarnings("unchecked")
private class DragListAdapter extends ArrayAdapter {
public DragListAdapter() {
super(DragActivity.this, R.layout.list_item, names);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_item, parent, false);
}
row.setDrawingCacheEnabled(true);
TextView name = (TextView) row.findViewById(R.id.item_text);
ImageView icon = (ImageView) row.findViewById(R.id.item_icon);
name.setText(names.get(position));
icon.setImageResource(icons.get(matching.get(position)));
return row;
}
}
private boolean checkOnDropIcon(MotionEvent me) {
ImageView drop_icon = (ImageView) findViewById(R.id.main_image);
Rect icon_rect = new Rect();
drop_icon.getGlobalVisibleRect(icon_rect);
Log.d(TAG, "icon at " + icon_rect.left + "<- ->" + icon_rect.right + ", " +
icon_rect.top + " ^ v" + icon_rect.bottom);
if ((me.getRawX()<icon_rect.left) || (me.getRawX()>icon_rect.right) ||
(me.getRawY()<icon_rect.top) || (me.getRawY()>icon_rect.bottom)) {
return false;
}
else {
return true;
}
}
private void checkOnDrop(MotionEvent me) {
boolean onDropIcon = checkOnDropIcon(me);
ImageView image = (ImageView) findViewById(R.id.main_image);
if ((onDropIcon) && (current_icon==R.drawable.notepad)) {
current_icon = R.drawable.exit;
image.setImageResource(current_icon);
image.invalidate();
return;
}
if ((!onDropIcon) && (current_icon==R.drawable.exit)) {
current_icon = R.drawable.notepad;
image.setImageResource(current_icon);
image.invalidate();
return;
}
}
public boolean onTouch(View view, MotionEvent me) {
if (state == NOT_DRAGGING) {
// get the position of the touch so we know where to place the dragging item if it is a long press
current_x = me.getRawX();
current_y = me.getRawY();
return false;
}
else {
FrameLayout frame = (FrameLayout) findViewById(R.id.drag_space);
if (me.getAction()==MotionEvent.ACTION_UP) {
frame.removeAllViews();
draggable=null;
frame.setVisibility(View.GONE);
state=NOT_DRAGGING;
// check if we dropped a name
if (checkOnDropIcon(me)) {
names.remove(dragged_position);
matching.remove(dragged_position);
ListView list = (ListView) findViewById(R.id.main_list);
DragListAdapter adapter = (DragListAdapter) list.getAdapter();
adapter.notifyDataSetChanged();
}
// restore the icon
ImageView image = (ImageView) findViewById(R.id.main_image);
current_icon = R.drawable.notepad;
image.setImageResource(current_icon);
image.invalidate();
}
if (me.getAction()==MotionEvent.ACTION_MOVE) {
int frame_position[] = new int[2];
frame.getLocationOnScreen(frame_position);
draggable.setPadding(
(int) me.getRawX()-frame_position[0]-(draggable.getDrawable().getIntrinsicWidth()/2),
(int) me.getRawY()-frame_position[1]-(draggable.getDrawable().getIntrinsicHeight()/2),
0, 0);
draggable.invalidate();
checkOnDrop(me);
}
return true;
}
}
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (state == DRAGGING) {
Log.d(TAG, "already have an object moving... ?");
return false;
}
FrameLayout frame = (FrameLayout) findViewById(R.id.drag_space);
int frame_position[] = new int[2];
frame.getLocationOnScreen(frame_position);
// setup everything for dragging
state = DRAGGING;
dragged_position = i;
draggable = new ImageView(this);
Bitmap bm = view.getDrawingCache();
draggable.setImageBitmap(bm);
draggable.setAlpha(150);
draggable.setScaleType(ImageView.ScaleType.CENTER);
draggable.setDrawingCacheEnabled(true);
draggable.setPadding((int) current_x-frame_position[0]-(bm.getWidth()/2), (int) current_y-frame_position[1]-(bm.getHeight()/2), 0, 0);
frame.setVisibility(View.VISIBLE);
frame.addView(draggable, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return true;
}
}

Android transfer touch event between views

Here is my issue.
I have about 7 buttons inside a linear layout and i am trying to "slide" between them highlighting each one as the finger passes over.
So far i have seen that the view that receives the action down event is locked in and receives every following motion event untill action up.
here is what i was trying:
public class LinearRoot extends LinearLayout {
#SuppressWarnings("unused")
private static final String TAG = LinearRoot.class.getSimpleName();
public LinearRoot(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private LinearRoot(Context context) {
super(context);
init();
}
private void init() {
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
for (int i = 0; i < getChildCount(); i++) {
Rect r = new Rect();
getChildAt(i).getHitRect(r);
Log.e(TAG, r.flattenToString());
map.put(r, getChildAt(i));
}
LinearRoot.this.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
/* (non-Javadoc)
* #see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
*/
View lastView;
private final HashMap<Rect, View> map = new HashMap<Rect, View>();
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
return false;
}
Rect rect = new Rect();
if (lastView != null) {
lastView.getGlobalVisibleRect(rect);
if (dispatchTouchToSpecificView(rect, ev)) {
lastView.dispatchTouchEvent(ev);
return false;
} else {
ev.setAction(MotionEvent.ACTION_CANCEL);
lastView.dispatchTouchEvent(ev);
}
}
Iterator<Rect> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
rect = iterator.next();
if (dispatchTouchToSpecificView(rect, ev)) {
lastView = map.get(rect);
map.get(rect).dispatchTouchEvent(ev);
return false;
}
}
return false;
}
private boolean dispatchTouchToSpecificView(Rect r, MotionEvent ev) {
Log.e(TAG, "X: " + (int) ev.getX() + " Y" + (int) ev.getY());
Log.e(TAG, r.flattenToString());
return r.contains((int) ev.getRawX(), (int) ev.getRawY());
}
}
This is the root layout for all the buttons, which delegates the touch events to the appropriate button by getting its global hit rectangle and seeing if the touch event is inside.
Right now this works only partially, and i am not satisfied with the solution, please provide some comments or possibilities to try.
What i am trying to achieve is a layout that has a large number of buttons which are pretty small and i want to highlight the touched ones before the release so the user can adjust his click.

Add button to a SlidingDrawer handle?

I've been working on this for a while. The Idea started simple, I wanted a button on a SlidingDrawer handle to allow the user to view settings specific to the content of the drawer. So I made a layout with a button off to the side and set it as the handle. The drawer drew fine, but would not allow the button (on the handle) to be pressed. When ever I try to click the thing, the click is interpreted as a handle click, and toggle the state of the drawer.
Does anyone know whats going on?
Thanks ~Aedon
I'll post my implementation, to save others the trouble.
You basically have to extend the SlidingDrawer class and handle the onInterceptTouch events to pass through when they're on top of items inside the handle layout.
This assumes you are using a ViewGroup (e.g. any layout) for the handle and all the views inside it are clickable.
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SlidingDrawer;
public class ClickableSlidingDrawer extends SlidingDrawer {
private ViewGroup mHandleLayout;
private final Rect mHitRect = new Rect();
public ClickableSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ClickableSlidingDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
View handle = getHandle();
if (handle instanceof ViewGroup) {
mHandleLayout = (ViewGroup) handle;
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mHandleLayout != null) {
int childCount = mHandleLayout.getChildCount();
int handleClickX = (int)(event.getX() - mHandleLayout.getX());
int handleClickY = (int)(event.getY() - mHandleLayout.getY());
Rect hitRect = mHitRect;
for (int i=0;i<childCount;i++) {
View childView = mHandleLayout.getChildAt(i);
childView.getHitRect(hitRect);
if (hitRect.contains(handleClickX, handleClickY)) {
return false;
}
}
}
return super.onInterceptTouchEvent(event);
}
}
Then, in your layout .xml just use <my.package.name.ClickableSlidingDrawer> instead of <SlidingDrawer>
I tried out d4n3's implementation, but since my handle contains a button that is nested within multiple ViewGroups, I had to modify it to make it work.
My implementations also assumes that you are using a ViewGroup for the handle, but the child views don't have to be clickable. Also, you have to set the tag to "click_intercepted" of the View(s) that you want to be clickable in the handle. Only child views with this specific tag set will be considered for clicks within the handle. This way, you can layout your handle anyway you want, and still act appropriately on clicks on specific Views (e.g. a Button) in the handle. Also, with this implementation, you can still both drag and click the handle to toggle its state.
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SlidingDrawer;
public class ClickableSlidingDrawer extends SlidingDrawer
{
private static final String TAG_CLICK_INTERCEPTED = "click_intercepted";
private ViewGroup mHandleLayout;
private final Rect mHitRect = new Rect();
public ClickableSlidingDrawer(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ClickableSlidingDrawer(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onFinishInflate()
{
super.onFinishInflate();
View handle = getHandle();
if (handle instanceof ViewGroup)
{
mHandleLayout = (ViewGroup) handle;
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event)
{
if (mHandleLayout != null)
{
int clickX = (int) (event.getX() - mHandleLayout.getLeft());
int clickY = (int) (event.getY() - mHandleLayout.getTop());
if (isAnyClickableChildHit(mHandleLayout, clickX, clickY))
{
return false;
}
}
return super.onInterceptTouchEvent(event);
}
private boolean isAnyClickableChildHit(ViewGroup viewGroup, int clickX, int clickY)
{
for (int i = 0; i < viewGroup.getChildCount(); i++)
{
View childView = viewGroup.getChildAt(i);
if (TAG_CLICK_INTERCEPTED.equals(childView.getTag()))
{
childView.getHitRect(mHitRect);
if (mHitRect.contains(clickX, clickY))
{
return true;
}
}
if (childView instanceof ViewGroup && isAnyClickableChildHit((ViewGroup) childView, clickX, clickY))
{
return true;
}
}
return false;
}
}
You can suppress the action that interprets a click on the handle button as an "open" with an attribute in the SlidingDrawer element in the layout XML. Like this:
<SlidingDrawer android:layout_width="fill_parent"android:id="#+id/SlidingDrawer" android:handle="#+id/slideHandleButton"
android:content="#+id/txtHolder" android:layout_height="fill_parent"
android:orientation="horizontal" android:allowSingleTap="false">
Just make the android:allowSingleTap="false" Then just implement a click handler for the button like you normally would. This will stop it from opening/closing the drawer, but you might need to intercept the events for the button to get it to do what YOU want it to do.
First make a layout and put your Handle content in it (say you put in handle_content.xml).
Second replace your current handle handle with this:
<include android:id="#id/handle"
android:layout="#layout/handle_content.xml"/>
Now do as below (I say this because below work correctly if u do as above)
This is my implementation:
package com.examples.my.views;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SlidingDrawer;
import com.examples.my.MainFragmentActivity;
public class MYSlidingDrawer extends SlidingDrawer {
private View button;
private int height;
private MainFragmentActivity activity;
public MYSlidingDrawer (Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
height = metrics.heightPixels;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int left = button.getLeft();
int top = button.getTop();
int right = button.getRight();
int bottom = button.getBottom();
Rect rect = new Rect(left, top, right, bottom);
int x = (int) event.getX();
int y = (int) event.getY();
if (isOpened()) {
if (rect.contains(x, y)) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (activity != null)
{
//HERE DO YOUR WORK
// Like activity.tooglePlay();
}
}
return true;
}
} else {
y -= height;
if (rect.contains(x, Math.abs(y))) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (activity != null)
{
//HERE DO YOUR WORK
// Like activity.tooglePlay();
}
}
return true;
}
}
return super.onTouchEvent(event);
}
public void setButton(View button) {
this.button = button;
}
public void setActivity(MainFragmentActivity activity) {
this.activity = activity;
}
}
And now define this in which you include MYSlidingDrawer:
MYSlidingDrawer drawer = (MYSlidingDrawer) findViewById(R.id.drawer);
drawer.setActivity(this);
Button btn = (Button) findViewById(R.id.play_btn);//button inside your handle
drawer.setButton(btn);
Hope this help you.

Categories

Resources