Supposing that I have two circles inside my onDraw() method.
protected void onDraw(Canvas canvas) {
canvas.drawCircle(redX, redY, redRad, redPaint);
canvas.drawCircle(cx, cy, rad, p);
}
nevermind of the variables that I have used, through the method provided by the View class onTouchEvent() I can put an action on a circle if it is alone, but what if I want them to have an on onTouchEvent() separately even though they are at the same onDraw() method, is it possible? What is the best way to do that?
I don't think this is possible as onTouchEvent is method of view class and you can override it only once.
Only thing you can do is to override ontouchEvent and then from its touch position you can find out in which area you are touching and do the operation that you need to do.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
upCell = -1;
xPos = event.getX();
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
xPos = event.getX();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
}
return super.onTouchEvent(event);
}
You need to store the position of each object & check for overlap every time the touch event for this view is invoked.
A sample is given below(Assuming your objects are circles):
public class CircleDrawingView extends View
{
//constructor - to be used when creating view from code
public CircleDrawingView(final Context ct) {
super(ct);
init();
}
//constructor - invoked when view is used in xml
public CircleDrawingView(final Context ct, final AttributeSet attrs) {
super(ct, attrs);
init();
}
//constructor - invoked when view is used in xml
public CircleDrawingView(final Context ct, final AttributeSet attrs, final int defStyle) {
super(ct, attrs, defStyle);
init();
}
Paint mCirclePaint;
ArrayList<CircleArea> allCircles;//list of all circles drawn on the view
private void init() {
allCircles = new ArrayList<>();
//CircleArea is a class defined below. It's constructor params are:
//CircleArea(int CenterX,int CenterY,int Radius,String TAG)
allCircles.add( new CircleArea(150,50,50, "C1"));
allCircles.add( new CircleArea(150,250,90, "C2"));
allCircles.add( new CircleArea(220,550,50, "C3"));
allCircles.add( new CircleArea(250,350,150, "C4"));
mCirclePaint = new Paint();
mCirclePaint.setColor(Color.BLACK);
mCirclePaint.setStyle(Paint.Style.FILL);
}
#Override
public void onDraw(final Canvas canv) {
canv.drawARGB(0, 0, 0, 0);
for (CircleArea obj : allCircles)
canv.drawCircle(obj.centerX, obj.centerY, obj.radius, mCirclePaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float xTouch = event.getX();
float yTouch = event.getY();
for (CircleArea obj : allCircles)
{
//Check if the touched co-ordinates lies in one of the drawn circle
if(Math.abs(obj.centerX-xTouch)<obj.radius && Math.abs(obj.centerY-yTouch)<obj.radius)
{
onTouch(obj.tag);
//return true; - If you want the touch event of other views to be invoked
//return false; - If you want to consume the touch event,
// i.e. touch event for other views will not be invoked
//Do not return if objects(circles) drawn on this view are overlapping
//and you want to invoke touch event for each object if such a scenario occurs
}
}
return super.onTouchEvent(event);
}
private void onTouch(String tag)
{
switch (tag)
{
case "C1":
//Touched circle 1
break;
case "C2":
//Touched circle 2
break;
case "C3":
//Touched circle 3
break;
case "C4":
//Touched circle 4
break;
default:
//Didnt touch any circle
}
}
/** Stores data about single circle */
private static class CircleArea {
int radius;
int centerX;
int centerY;
String tag;
CircleArea(int centerX, int centerY, int radius, String tag) {
this.radius = radius;
this.centerX = centerX;
this.centerY = centerY;
this.tag = tag;
}
}
}
I am using an EditText widget and would like to modify the context menu that is displayed when the user long presses the view. The problem that I am having is that I need to know the character position within the text of the long press so I can determine what I need to add to the context menu. The base class is doing this because one of the choices in the menu is 'Add “word_clicked_on” To Dictionary.' Setting ClickableSpans within the text does not appear to be a solution since it consumes the click event which makes it impossible to move the edit cursor within the spans.
Here is the solution that I came up with and it does work so I wanted to share it:
First I concluded that I needed to extend the EditText class so that I could intercept the onTouchEvent, capture the ACTION_DOWN event, and save the position. Now that I have the position of the down point I can call getOffsetForPosition(downPointX, downPointY) and get the character position of the long-press. There is one big problem, getOffsetForPosition was not added until SDK 14! To make this solution work I had to back port the functionality of getOffsetForPosition and branch if the current SDK is earlier than SDK_INT 14. Here is the source code for the new class:
public class ScrapEditText extends EditText{
protected float LastDownPositionX, LastDownPositionY;
public ScrapEditText(Context context)
{
super(context);
}
public ScrapEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
final int action = event.getActionMasked();
if(action == MotionEvent.ACTION_DOWN)
{
LastDownPositionX = event.getX();
LastDownPositionY = event.getY();
}
return super.onTouchEvent(event);
}
public float GetLastDownPositionX()
{
return LastDownPositionX;
}
public float GetLastDownPositionY()
{
return LastDownPositionY;
}
public int GetOffsetForLastDownPosition()
{
if(Build.VERSION.SDK_INT > 13)
{
// as of SDK 14 the getOffsetForPosition was added to TextView
return getOffsetForPosition(LastDownPositionX, LastDownPositionY);
}
else
{
return GetOffsetForPositionOlderSdk();
}
}
public int GetOffsetForPositionOlderSdk()
{
if (getLayout() == null) return -1;
final int line = GetLineAtCoordinateOlderSDK(LastDownPositionY);
final int offset = GetOffsetAtCoordinateOlderSDK(line, LastDownPositionX);
return offset;
}
public int GetLineAtCoordinateOlderSDK(float y)
{
y -= getTotalPaddingTop();
// Clamp the position to inside of the view.
y = Math.max(0.0f, y);
y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
y += getScrollY();
return getLayout().getLineForVertical((int) y);
}
protected int GetOffsetAtCoordinateOlderSDK(int line, float x) {
x = ConvertToLocalHorizontalCoordinateOlderSDK(x);
return getLayout().getOffsetForHorizontal(line, x);
}
protected float ConvertToLocalHorizontalCoordinateOlderSDK(float x) {
x -= getTotalPaddingLeft();
// Clamp the position to inside of the view.
x = Math.max(0.0f, x);
x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
x += getScrollX();
return x;
}
}
In your Activity derived class:
ScrapText = (ScrapEditText) findViewById(R.id.sample_text);
ScrapText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
int charOffset = FileText.GetOffsetForLastDownPosition();
}
});
I'm using a ScrollView in Android and where the visible portion of the ScrollView is the same size as one of the cells inside the Scrollview. Every "cell" is the same height. So what I am trying to do is snap into position after the ScrollView has been scrolled.
Currently I am detecting when the user has touched the ScrollView and when they've started scrolling and working it out from there, but it is quite buggy. It also needs to work when the user just flicks it and it scrolls and then decelerates.
On iPhone there is a function that is something like didDecelerate and there I can do any code I want when the ScrollView has finished scrolling. Is there such a thing with Android? Or is there some code I could look at to figure out a better way of doing it?
I've looked over the Android docs and could not find anything like that.
I recently had to implement the function you described. What i did was to have a Runnable checking out if the ScrollView had stopped scrolling by comparing the value returned by getScrollY() when the onTouchEvent is first triggered with the value returned after a time defined by the variable newCheck.
See code below (working solution):
public class MyScrollView extends ScrollView{
private Runnable scrollerTask;
private int initialPosition;
private int newCheck = 100;
private static final String TAG = "MyScrollView";
public interface OnScrollStoppedListener{
void onScrollStopped();
}
private OnScrollStoppedListener onScrollStoppedListener;
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
scrollerTask = new Runnable() {
public void run() {
int newPosition = getScrollY();
if(initialPosition - newPosition == 0){//has stopped
if(onScrollStoppedListener!=null){
onScrollStoppedListener.onScrollStopped();
}
}else{
initialPosition = getScrollY();
MyScrollView.this.postDelayed(scrollerTask, newCheck);
}
}
};
}
public void setOnScrollStoppedListener(MyScrollView.OnScrollStoppedListener listener){
onScrollStoppedListener = listener;
}
public void startScrollerTask(){
initialPosition = getScrollY();
MyScrollView.this.postDelayed(scrollerTask, newCheck);
}
}
Then i have:
scroll.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
scroll.startScrollerTask();
}
return false;
}
});
scroll.setOnScrollStoppedListener(new OnScrollStoppedListener() {
public void onScrollStopped() {
Log.i(TAG, "stopped");
}
});
Here is yet another fix to the, IMHO, missing OnEndScroll event bug in the ScrollView.
Its inspired by hambonious answer.
Simply drop this class into your project (change package to match your own) and use the below xml
package com.thecrag.components.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class ResponsiveScrollView extends ScrollView {
public interface OnEndScrollListener {
public void onEndScroll();
}
private boolean mIsFling;
private OnEndScrollListener mOnEndScrollListener;
public ResponsiveScrollView(Context context) {
this(context, null, 0);
}
public ResponsiveScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ResponsiveScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void fling(int velocityY) {
super.fling(velocityY);
mIsFling = true;
}
#Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
if (mIsFling) {
if (Math.abs(y - oldY) < 2 || y >= getMeasuredHeight() || y == 0) {
if (mOnEndScrollListener != null) {
mOnEndScrollListener.onEndScroll();
}
mIsFling = false;
}
}
}
public OnEndScrollListener getOnEndScrollListener() {
return mOnEndScrollListener;
}
public void setOnEndScrollListener(OnEndScrollListener mOnEndScrollListener) {
this.mOnEndScrollListener = mOnEndScrollListener;
}
}
again changing the package name to match your project
<com.thecrag.components.ui.ResponsiveScrollView
android:id="#+id/welcome_scroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/welcome_scroll_command_help_container"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/welcome_header_text_thecrag"
android:layout_margin="6dp">
....
</com.thecrag.components.ui.ResponsiveScrollView>
I subclassed (Horizontal)ScrollView and did something like this:
#Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
if (Math.abs(x - oldX) > SlowDownThreshold) {
currentlyScrolling = true;
} else {
currentlyScrolling = false;
if (!currentlyTouching) {
//scrolling stopped...handle here
}
}
super.onScrollChanged(x, y, oldX, oldY);
}
I used a value of 1 for the SlowDownThreshold since it always seems to be the difference of the last onScrollChanged event.
In order to make this behave correctly when dragging slowly, I had to do this:
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
currentlyTouching = true;
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
currentlyTouching = false;
if (!currentlyScrolling) {
//I handle the release from a drag here
return true;
}
}
return false;
}
My approach is determine scrolling state by a timestamp changed each time the onScrollChanged() is called.
It's very easy to determine when is start and end of scrolling.
You can also change threshold ( I use 100ms ) to fix sensitivity.
public class CustomScrollView extends ScrollView {
private long lastScrollUpdate = -1;
private class ScrollStateHandler implements Runnable {
#Override
public void run() {
long currentTime = System.currentTimeMillis();
if ((currentTime - lastScrollUpdate) > 100) {
lastScrollUpdate = -1;
onScrollEnd();
} else {
postDelayed(this, 100);
}
}
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (lastScrollUpdate == -1) {
onScrollStart();
postDelayed(new ScrollStateHandler(), 100);
}
lastScrollUpdate = System.currentTimeMillis();
}
private void onScrollStart() {
// do something
}
private void onScrollEnd() {
// do something
}
}
Here is yet another solution, quite simple and clean in my opinion, naturally inspired by answers above. Basically once user ended gesture check if getScrollY() is still changing, after a brief delay (here 50ms).
public class ScrollViewWithOnStopListener extends ScrollView {
OnScrollStopListener listener;
public interface OnScrollStopListener {
void onScrollStopped(int y);
}
public ScrollViewWithOnStopListener(Context context) {
super(context);
}
public ScrollViewWithOnStopListener(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_UP:
checkIfScrollStopped();
}
return super.onTouchEvent(ev);
}
int initialY = 0;
private void checkIfScrollStopped() {
initialY = getScrollY();
this.postDelayed(new Runnable() {
#Override
public void run() {
int updatedY = getScrollY();
if (updatedY == initialY) {
//we've stopped
if (listener != null) {
listener.onScrollStopped(getScrollY());
}
} else {
initialY = updatedY;
checkIfScrollStopped();
}
}
}, 50);
}
public void setOnScrollStoppedListener(OnScrollStopListener yListener) {
listener = yListener;
}
}
My approach for this question is to use a timer to check for the following 2 "events".
1) onScrollChanged() stopped being called
2) User's finger is lift from the scrollview
public class CustomScrollView extends HorizontalScrollView {
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
Timer ntimer = new Timer();
MotionEvent event;
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
checkAgain();
super.onScrollChanged(l, t, oldl, oldt);
}
public void checkAgain(){
try{
ntimer.cancel();
ntimer.purge();
}
catch(Exception e){}
ntimer = new Timer();
ntimer.schedule(new TimerTask() {
#Override
public void run() {
if(event.getAction() == MotionEvent.ACTION_UP){
// ScrollView Stopped Scrolling and Finger is not on the ScrollView
}
else{
// ScrollView Stopped Scrolling But Finger is still on the ScrollView
checkAgain();
}
}
},100);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.event = event;
return super.onTouchEvent(event);
}
}
For a simple case like you described, you can probably get away with overriding fling method in your custom scroll view. Fling method gets called to perform "deceleration" every time user raises his finger from the screen.
So what you should do is something like this:
Subclass ScrollView.
public class MyScrollView extends ScrollView {
private Scroller scroller;
private Runnable scrollerTask;
//...
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
scroller = new Scroller(getContext()); //or OverScroller for 3.0+
scrollerTask = new Runnable() {
#Override
public void run() {
scroller.computeScrollOffset();
scrollTo(0, scroller.getCurrY());
if (!scroller.isFinished()) {
MyScrollView.this.post(this);
} else {
//deceleration ends here, do your code
}
}
};
//...
}
}
Subclass fling method and DO NOT call superclass implementation.
#Override
public void fling(int velocityY) {
scroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0, container.getHeight());
post(scrollerTask);
//add any extra functions you need from android source code:
//show scroll bars
//change focus
//etc.
}
Fling will not trigger if the user stops scrolling before raising up his finger (velocityY == 0). In case you want to intercept this sort of events aswell, override onTouchEvent.
#Override
public boolean onTouchEvent(MotionEvent ev) {
boolean eventConsumed = super.onTouchEvent(ev);
if (eventConsumed && ev.getAction() == MotionEvent.ACTION_UP) {
if (scroller.isFinished()) {
//do your code
}
}
return eventConsumed;
}
NOTE Although this works, overriding fling method might be a bad idea. It is public, but its barely designed for subclassing. Right now it does 3 things - it initiates fling for private mScroller, handles possible focus changes and shows scroll bars. This might change in future android release. For instance, private mScroller instance changed its class from Scroller to OvershootScroller between 2.3 and 3.0. You have to keep in mind all this small differences. In any case, be ready for unforeseen consequences in the future.
My solution is a variation of Lin Yu Cheng's great solution and also detects when scrolling has started and stopped.
Step 1. Define a HorizontalScrollView and OnScrollChangedListener:
CustomHorizontalScrollView scrollView = (CustomHorizontalScrollView) findViewById(R.id.horizontalScrollView);
horizontalScrollListener = new CustomHorizontalScrollView.OnScrollChangedListener() {
#Override
public void onScrollStart() {
// Scrolling has started. Insert your code here...
}
#Override
public void onScrollEnd() {
// Scrolling has stopped. Insert your code here...
}
};
scrollView.setOnScrollChangedListener(horizontalScrollListener);
Step 2. Add the CustomHorizontalScrollView class:
public class CustomHorizontalScrollView extends HorizontalScrollView {
public interface OnScrollChangedListener {
// Developer must implement these methods.
void onScrollStart();
void onScrollEnd();
}
private long lastScrollUpdate = -1;
private int scrollTaskInterval = 100;
private Runnable mScrollingRunnable;
public OnScrollChangedListener mOnScrollListener;
public CustomHorizontalScrollView(Context context) {
this(context, null, 0);
init(context);
}
public CustomHorizontalScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init(context);
}
public CustomHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
// Check for scrolling every scrollTaskInterval milliseconds
mScrollingRunnable = new Runnable() {
public void run() {
if ((System.currentTimeMillis() - lastScrollUpdate) > scrollTaskInterval) {
// Scrolling has stopped.
lastScrollUpdate = -1;
//CustomHorizontalScrollView.this.onScrollEnd();
mOnScrollListener.onScrollEnd();
} else {
// Still scrolling - Check again in scrollTaskInterval milliseconds...
postDelayed(this, scrollTaskInterval);
}
}
};
}
public void setOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener) {
this.mOnScrollListener = onScrollChangedListener;
}
public void setScrollTaskInterval(int scrollTaskInterval) {
this.scrollTaskInterval = scrollTaskInterval;
}
//void onScrollStart() {
// System.out.println("Scroll started...");
//}
//void onScrollEnd() {
// System.out.println("Scroll ended...");
//}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mOnScrollListener != null) {
if (lastScrollUpdate == -1) {
//CustomHorizontalScrollView.this.onScrollStart();
mOnScrollListener.onScrollStart();
postDelayed(mScrollingRunnable, scrollTaskInterval);
}
lastScrollUpdate = System.currentTimeMillis();
}
}
}
Try taking a look at this question here on StackOverflow - it's not exactly the same as your question, but it gives an idea on how you can manage the scroll event of a ScrollView.
Basicly you need to create your own CustomScrollView by extending ScrollView and override onScrollChanged(int x, int y, int oldx, int oldy). Then you need to reference this in your layout file instead of the standard ScrollView like com.mypackage.CustomScrollView.
There are some great answers here, but my code can detect when scrolling stops without having to extend ScrollView class.
every view instance can call getViewTreeObserver(). when Holding this instance of ViewTreeObserver you can add a OnScrollChangedListener using the function addOnScrollChangedListener().
declare the following:
private ScrollView scrollListener;
private volatile long milesec;
private Handler scrollStopDetector;
private Thread scrollcalled = new Thread() {
#Override
public void run() {
if (System.currentTimeMillis() - milesec > 200) {
//scroll stopped - put your code here
}
}
};
and in your onCreate (or another place) add:
scrollListener = (ScrollView) findViewById(R.id.scroll);
scrollListener.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
#Override
public void onScrollChanged() {
milesec = System.currentTimeMillis();
scrollStopDetector.postDelayed(scrollcalled, 200);
}
});
you might want to take longer or slower time between this checks, but when scrolling this listner gets called really fast so it will work very fast.
Here's my solution which includes scroll tracking and scroll ending:
public class ObservableHorizontalScrollView extends HorizontalScrollView {
public interface OnScrollListener {
public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
public void onEndScroll(ObservableHorizontalScrollView scrollView);
}
private boolean mIsScrolling;
private boolean mIsTouching;
private Runnable mScrollingRunnable;
private OnScrollListener mOnScrollListener;
public ObservableHorizontalScrollView(Context context) {
this(context, null, 0);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
if (action == MotionEvent.ACTION_MOVE) {
mIsTouching = true;
mIsScrolling = true;
} else if (action == MotionEvent.ACTION_UP) {
if (mIsTouching && !mIsScrolling) {
if (mOnScrollListener != null) {
mOnScrollListener.onEndScroll(this);
}
}
mIsTouching = false;
}
return super.onTouchEvent(ev);
}
#Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
if (Math.abs(oldX - x) > 0) {
if (mScrollingRunnable != null) {
removeCallbacks(mScrollingRunnable);
}
mScrollingRunnable = new Runnable() {
public void run() {
if (mIsScrolling && !mIsTouching) {
if (mOnScrollListener != null) {
mOnScrollListener.onEndScroll(ObservableHorizontalScrollView.this);
}
}
mIsScrolling = false;
mScrollingRunnable = null;
}
};
postDelayed(mScrollingRunnable, 200);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);
}
}
public OnScrollListener getOnScrollListener() {
return mOnScrollListener;
}
public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
this.mOnScrollListener = mOnEndScrollListener;
}
}
I think this has come up in the past. AFAIK, you can't easily detect that. My suggestion is that you take a look at ScrollView.java (that's how we do things in Android land :)) and figure out how you can extend the class to provide the functionality you are looking for. This is what I would try first:
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
if (mScroller.isFinished()) {
// do something, for example call a listener
}
}
this is an old thread but I'd like to add a shorter solution I came up with:
buttonsScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
handler.removeCallbacksAndMessages(null)
handler.postDelayed({
//YOUR CODE TO BE EXECUTED HERE
},1000)
}
Naturally there's a 1000 milliseconds delay. Adjust that if you need to.
I've made some improvements to ZeroG's answer. Mainly cancellation of excess task calls and implementing the whole thing as a private OnTouchListener, so all the scroll detection code would be in one place.
Paste the following code into your own ScrollView implementation:
private class ScrollFinishHandler implements OnTouchListener
{
private static final int SCROLL_TASK_INTERVAL = 100;
private Runnable mScrollerTask;
private int mInitialPosition = 0;
public ScrollFinishHandler()
{
mScrollerTask = new Runnable() {
public void run() {
int newPosition = getScrollY();
if(mInitialPosition - newPosition == 0)
{//has stopped
onScrollStopped(); // Implement this on your main ScrollView class
}else{
mInitialPosition = getScrollY();
ExpandingLinearLayout.this.postDelayed(mScrollerTask, SCROLL_TASK_INTERVAL);
}
}
};
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_UP)
{
startScrollerTask();
}
else
{
stopScrollerTask();
}
return false;
}
}
And then in your ScrollView implementation:
setOnTouchListener( new ScrollFinishHandler() );
this.getListView().setOnScrollListener(new OnScrollListener(){
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if( firstVisibleItem + visibleItemCount >= totalItemCount )
// Last item is shown...
}
Hope the snippet help :)
I searched all over, but could not find a solution.
I have a view (lets call it myView) inside a scrollview. myView is bigger than the screen. Since I'm able to get the relative x,y position of my finger inside myView, I would like to make the scrollView autoscroll to the top/bottom when my finger enters a certain top/bottom threshold.
I have some ideas, namely translating the drag location to the screen position but this did not solve this problem.
thanks in advance
cheers
All right I figured it out by myself.
First I had to extend the ScrollView class and added an interface OnScrollViewListener.
public class MyScrollView extends ScrollView {
private OnScrollViewListener mListener;
public MyScrollView(Context c, AttributeSet attrs) {
super(c, attrs);
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mListener != null) {
mListener.onScrollChanged((OnScrollViewListener) this);
}
}
public void setOnScrollViewListener(OnScrollViewListener listener) {
mListener = listener;
}
public static interface OnScrollViewListener {
public void onScrollChanged(OnScrollViewListener listener);
}
}
Next in my Activity I inserted a member mScrollDistance that indicates the amount of
pixels the user scrolls.
public class ScrollActivity extends Activity {
private int mScrollDistance;
#Override
protected void OnCreate(...) {
...
final MyScrollView myScrollView = (MyScrollView) findViewById(R.id.scroll_view);
myScrollView.setOnScrollViewListener(new MyScrollView.OnScrollViewListener() {
public void onScrollChanged(OnScrollViewListener listener) {
mScrollDistance = listener.getScrollY();
}
}
// making an drag and drop in an view that is inside the MyScrollView
final LinearLayout myLayout = (LinearLayout)findViewById(R.id.linear_layout);
myLayout.setOnDragListener(new View.OnDragListener() {
public boolean onDrag (View v, DragEvent event) {
int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED: {
}
case DragEvent.ACTION_DRAG_LOCATION: {
int y = Math.round(event.getY());
int translatedY = y - mScrollDistance;
int threshold = 50;
// make a scrolling up due the y has passed the threshold
if (translatedY < threshold) {
// make a scroll up by 30 px
myScrollView.scrollBy(0, -30);
}
// make a autoscrolling down due y has passed the 500 px border
if (translatedY + threshold > 500) {
// make a scroll down by 30 px
myScrollView.scrollBy(0, 30);
}
// listen for more actions here
// ...
}
}
}
}
Now, mScrollDistance gets always a new value and the drag location will be translated to the view location.
I tested this and it works on layouts/views that are bigger than the screen size.
Hope that helps.
I came up with a different solution and I am happy with it.
I want to be able to drag and drop views inside a ScrollView. The ScrollView then needs to scroll up and down automatically when the shadow reaches the edges of the scroll view.
I ended up with a solution that detects wether the drop zone is completely visible inside the scrollview (with a 100px margin) and adjust the scroll view otherwise.
#Override
public boolean onDrag(View view, DragEvent event) {
MainWidget dropZoneView = (MainWidget) view;
int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
//(... other stuff happens here)
case DragEvent.ACTION_DRAG_LOCATION:
ScrollView mainScrollView = (ScrollView) findViewById(R.id.main_scroll);
int topOfDropZone = dropZoneView.getTop();
int bottomOfDropZone = dropZoneView.getBottom();
int scrollY = mainScrollView.getScrollY();
int scrollViewHeight = mainScrollView.getMeasuredHeight();
Log.d(LOG_TAG,"location: Scroll Y: "+ scrollY + " Scroll Y+Height: "+(scrollY + scrollViewHeight));
Log.d(LOG_TAG," top: "+ topOfDropZone +" bottom: "+bottomOfDropZone);
if (bottomOfDropZone > (scrollY + scrollViewHeight - 100))
mainScrollView.smoothScrollBy(0, 30);
if (topOfDropZone < (scrollY + 100))
mainScrollView.smoothScrollBy(0, -30);
break;
default:
break;
}
return true;
}
Hope this helps!
I used a timer in In C#
ScrollCalendar ScrollCalendar = new ScrollCalendar (yourScrollView);
Inside the drag event
public bool OnDrag (View v, DragEvent e)
{
var dragshadow = new EventDateDragShadow (v);
switch (e.Action) {
case DragAction.Started:
return true;
case DragAction.Entered:
break;
case Android.Views.DragAction.Location:
if (e.GetY () < 90) {
ScrollCalendar.StartScroll (-15);
} else if (e.GetY () > yourScrollView.Height - 90) {
ScrollCalendar.StartScroll (15);
} else
ScrollCalendar.StopScroll ();
return (true);
case DragAction.Exited:
return true;
case DragAction.Drop:
return true;
case DragAction.Ended:
ScrollCalendar.StopScroll ();
v.SetOnDragListener (null);
return true;
}
return true;
}
The ScrollCalendar class
public class ScrollCalendar
{
private ScrollView Calendar;
private System.Timers.Timer Timer;
private int ScrollDistance;
public ScrollCalendar(ScrollView calendar)
{
Calendar = calendar;
Timer = new System.Timers.Timer();
Timer.Elapsed+=new ElapsedEventHandler(Scroll);
Timer.Interval = 50;
}
public void StartScroll(int scrollDistance)
{
if (Timer.Enabled) {
return;
}
ScrollDistance = scrollDistance;
Timer.Enabled = true;
}
public void StopScroll()
{
Timer.Enabled = false;
}
private void Scroll(object source, ElapsedEventArgs e)
{
Calendar.SmoothScrollBy (0, ScrollDistance);
}
}
Change the StartScroll value and the Timer.Interval to adjust the speed of the scroll.
I have modified answer of Tiago A.
I faced the same problem and the solution from Tiago A was small and easy but have some limitation so if others require this may help.
Thanks to Tiago A.
case DragEvent.ACTION_DRAG_LOCATION:
ScrollView myScrollView =findViewById(R.id.myScrollView);
int topOfDropZone = myScrollView.getChildAt(0).getTop();
int bottomOfDropZone = myScrollView.getChildAt(0).getBottom();
int scrollY = myScrollView.getScrollY();
int scrollViewHeight = myScrollView.getMeasuredHeight();
if (Math.round(event.getY()) > scrollViewHeight - (scrollViewHeight / 45))
if (bottomOfDropZone > (scrollY + scrollViewHeight - 100))
myScrollView.smoothScrollBy(0, 30);
if (Math.round(event.getY()) < (scrollViewHeight / 45))
if (topOfDropZone < (scrollY + 100))
myScrollView.smoothScrollBy(0, -30);
return true;
I am making a grid-based game that will be much larger than the screen, and the user would scroll around in it. I basically put a bunch on ImageViews inside of a custom class that extends a relative layout. The problem is that even though RelativeLayout.LayoutParams is set to the correct size I want (1280*1280). The images are crammed against the sides of the screen and don't extend past it. I have got the scrolling logic working, and when I scroll, I can see it is a rectangle of images the size of one screen. How can I make it so the images extend past the screen?
The class that extends a relative layout:
public class GameGrid extends RelativeLayout {
ImageView[][] subViews;
int rows=0, cols=0, cellsize=0;
int width, height;
//Dragging variables
float startX;
float startY;
float lastX;
float lastY;
boolean touching;
boolean dragging;
int clickedChild;
public GameGrid(Context context) {
super(context);
init();
}
public GameGrid(Context context, int rws, int cls, int clsze) {
super(context);
rows=rws;
cols=cls;
cellsize=clsze;
init();
}
public GameGrid(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GameGrid(Context context, AttributeSet attrs, int defaultStyles) {
super(context, attrs, defaultStyles);
init();
}
public void init() {
rows=10;
cols=10;
cellsize=128;
startX = 0;
startY = 0;
lastX=0;
lastY=0;
touching = false;
dragging = false;
clickedChild = -1;
subViews = new ImageView[cols][rows];
setLayoutParams(new RelativeLayout.LayoutParams(cellsize*cols,cellsize*rows));
width=this.getLayoutParams().width;
height=this.getLayoutParams().height;
this.setMinimumWidth(width);
this.setMinimumHeight(height);
Log.i("info","****************");
Log.i("info","GameGrid Made.");
Log.i("info","width: "+width+"\nheight: "+height);
Log.i("info","****************");
makeGrid();
// this.setOnTouchListener()
}
public boolean getDragging(){
return dragging;
}
public void makeGrid() {
for(int y=0;y<rows;y++){
for(int x=0;x<cols;x++){
ImageView temp = new ImageView(getContext());
temp.setImageResource(R.drawable.water1);
temp.setScaleType(ImageView.ScaleType.FIT_XY);
RelativeLayout.LayoutParams temp2 = new RelativeLayout.LayoutParams(width/cols,height/rows);
if (x == 0 && y == 0){ //If this is the first view being made, set it relative to the parent.
temp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
temp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
else if (x == 0){ //If this is in the first column, set it below the one above.
temp2.addRule(RelativeLayout.ALIGN_LEFT,subViews[0][y-1].getId());
temp2.addRule(RelativeLayout.BELOW,subViews[0][y-1].getId());
}
else { //Align the bottom with first one of that row.
temp2.addRule(RelativeLayout.RIGHT_OF,subViews[x-1][y].getId());
temp2.addRule(RelativeLayout.ALIGN_BOTTOM,subViews[0][y].getId());
}
temp.setLayoutParams(temp2);
subViews[x][y]=temp;
subViews[x][y].setId(x+y*cols+1);
// Toast.makeText(getContext(), "" + v.getId(), Toast.LENGTH_SHORT).show();
subViews[x][y].setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v,MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
clickedChild = v.getId();
return false;
}
});
addView(temp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{ // when the user touches the screen
startX = event.getX();
startY = event.getY();
lastX = event.getX();
lastY = event.getY();
touching = true;
dragging = false;
return true;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE)
{ // when the user moves the touch
if (!dragging)
dragging = true;
int distX = (int)(event.getX()-lastX);
int distY = (int)(event.getY()-lastY);
this.scrollBy(-distX, -distY);
lastX = event.getX();
lastY = event.getY();
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{ // when the user lifts the touch
if (!dragging){
if (clickedChild>0){
Toast.makeText(getContext(), "getHeight()= " + getHeight(), Toast.LENGTH_SHORT).show();
clickedChild = -1;
}
}
touching = false;
dragging = false;
return true;
}
else if (event.getAction() == MotionEvent.ACTION_CANCEL)
{ // if something gets lost in translation
startX = 0;
startY = 0;
lastX=0;
lastY=0;
touching = false;
dragging = false;
return true;
}
return false;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth, parentHeight);
}
The Activity:
public class Attacktics2 extends Activity {
/** Called when the activity is first created. */
GameGrid grid;
int rows, cols, cellsize;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
public void start(View view) {
view.setVisibility(View.GONE);
grid = new GameGrid(this,10,10,128);
setContentView(grid);
}
}
Since you're already doing the heavy lifting of managing all the scrolling, I'd suggest that you implement your entire layout logic yourself and not rely on RelativeLayout. Except for ScrollView and HorizontalScrollView, the stock layout classes are going to restrict their children to be within the parent bounds. Those, in turn, will be restricted to the screen dimensions. If you handle the layout logic yourself, you can position child views so that they extend off screen. It then forms a viewport into a larger grid and can just render those children that are visible within the viewport.