get Centered Axis from MotionEvent - Android User Interface

Android examples for User Interface:Key Event

Description

get Centered Axis from MotionEvent

Demo Code

/*/* ww  w.  ja v  a2 s  . c om*/
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by Summers Pittman
 *
 */
//package com.java2s;

import android.view.InputDevice;

import android.view.MotionEvent;

public class Main {
    public static float getCenteredAxis(MotionEvent event,
            InputDevice device, int axis, int historyPos) {
        if (device == null) {
            return 0;
        }
        final InputDevice.MotionRange range = device.getMotionRange(axis,
                event.getSource());
        if (range != null) {
            final float flat = range.getFlat();
            final float value = historyPos < 0 ? event.getAxisValue(axis)
                    : event.getHistoricalAxisValue(axis, historyPos);

            // Ignore axis values that are within the 'flat' region of the
            // joystick axis center.
            // A joystick at rest does not always report an absolute position of
            // (0,0).
            if (Math.abs(value) > flat) {
                return value;
            }
        }
        return 0;
    }
}

Related Tutorials