How would I use the OnTouchEvent
function to make an ImageView
move to the right or left when the user touches the right or left of the screen? The following code is what I have tried. What could I do to improve this and make it work?
ImageView circle1 = (ImageView) findViewById(R.id.circle1);
public boolean onTouchEvent(MotionEvent MotionEvent motionEvent;
motionEvent){
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
// Player has touched the screen
case MotionEvent.ACTION_DOWN:
if (motionEvent.getY() > screenHeight - screenWidth / 8) {
circleIsMovingRIGHT = true;
circleIsMovingLEFT = false;
} else {
circleIsMovingRIGHT = false;
circleIsMovingLEFT = true;
}
break;
}
return true;
}
}
Try this,
@SuppressLint("ClickableViewAccessibility")
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
anyView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.anyView:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// perform here
}
break;
}
return false;
}
add this code in res/anim/rotate.xml
<?xml version="1.0" encoding="UTF-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:duration="1200"
android:interpolator="@android:anim/linear_interpolator"/>
Add This code at "//perform here" for rotate view (Component)
imageView.startAnimation(AnimationUtils.loadAnimation(context,R.anim.rotate));
if you are use android:repeatCount="infinite" then you will stop the rotation dynamically, apply this code on specific condition
imageView.clearAnimation();