mathexplorer mathexplorer - 2 months ago 7
Android Question

OnTouch not running when touched

I'm not getting any errors when I run my code, but nothing happens I touch the screen. The value of the global variable select should change but nothing happens.

Here is the code

public class NonmultiplierSixGame extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nonmultiplier_six_game);
}
}


activity_nonmultiplier_six_game:

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alexandermain.example_5.NonmultiplierSixGame">





<com.example.alexandermain.example_5.views.NonmultiplierSixView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/nonmultiplierSixView"
android:background="@color/colorPrimary"
/>


</android.support.constraint.ConstraintLayout>


NonmultiplierSixView class:

public class NonmultiplierSixView extends View implements View.OnTouchListener{



@Override
protected void onDraw(Canvas canvas){
//bunch of shapes
}


@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
Globals.SetSelect(1);
break;
case MotionEvent.ACTION_UP:
Globals.SetSelect(2);
break;

}

return true;
}



public NonmultiplierSixView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}


Edit:
Here is the Globals class
public class Globals {

public static int select=-2;
public static void SetSelect(int t) {
select = t;
}
public static int GetSelect() {
return(select);
}


}

Answer Source

When you implement OntouchListener, you need to setThe listener on your Context.

Simply add it in your constructor: It should be like this:

public NonmultiplierSixView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnTouchListener(this);
}