Assuming that if you make an upward movement you raise the volume and if you make a downward movement you lower the volume. Based on the above, we would work with the coordinates of the Y axis.
It is important to remember that in Android the coordinates are indicated in this way, in the upper left corner we have X = 0, Y = 0 and it is going to increase Y downwards and X to the right:
To do what you want, you must first obtain the value of Y and compare it with posInicial
, after the comparison you store the value of y in the variable posInicial
.
With this you can do what you want, remember that the listener to use the onTouch () method is OnTouchListener () .
I add an example, assuming having a LinearLayout
as a background in our main layout activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/my_layout">
</LinearLayout>
Within our Activity that loads the layout we obtain the reference and assign the listener:
LinearLayout my_layout = (LinearLayout)findViewById(R.id.my_layout);
my_layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
float x = event.getX();
float y = event.getY();
if(posInicial > y){
Log.i("Volumen", "Sube volumen!");
//tvUsurio.setText(volumen+1);
}else if (posInicial < y){
Log.i("Volumen", "Baja volumen!");
//tvUsurio.setText("Bajo volumne");
}
//Despues de evaluar si va hacia arriba o hacia abajo almacenamos el valor de la variable.
posInicial = y;
return true;
}
});