Rendy
Rendy

Reputation: 5698

Listen inside a view programmatically?

Is there any way to listen when user finger is inside a view programmatically? What I want is when user finger inside a view has different state when user moves their finger outside the view.

I know this can be done by xml, but because I'm using 3rd party library, it doesn't allow me to do so, so I must find a way to do it programmatically.

Upvotes: 1

Views: 111

Answers (1)

Ty Smith
Ty Smith

Reputation: 2594

Set a touch listener on the view and compare the x and y spots

http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent)

Record when the starting positon where the user touches down

http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_DOWN

and then track the offset.

here is some view listener code I wrote for another question:

float initialX = 0;
float initialY = 0;
int currentFocusedChild = 0;
List<View> children;

public void walkElements() {
    final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
    children = mainLayout.getFocusables(View.FOCUS_FORWARD);
    mainLayout.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = event.getX();
                    initialY = event.getY();                        
                    break;
                case MotionEvent.ACTION_MOVE:
                    float diffX = event.getX() - initialX;
                    float diffY = event.getY() - initialY;

                    if(diffY > 0) {
                        if (currentFocusedChild < children.size() - 1) {
                            currentFocusedChild++;
                        }
                    } else {
                        if (currentFocusedChild > 0) {
                            currentFocusedChild--;
                        }
                    }
                    children.get(currentFocusedChild).setSelected(true);

                    //Sleep for a period of time so the selection is slow enough for the user.
                    Thread.sleep(300);
                    break;
                case MotionEvent.ACTION_UP:
                    children.get(currentFocusedChild).performClick();
                    break;
            }
            return false;
        }
    });

}

Upvotes: 1

Related Questions