ともちゃんのアプリ開発日記

組込みC言語プログラマだったともちゃんが、四苦八苦しながら、AndroidのJAVA/Kotlin、iOSのSwiftUIを習得して行きます。ともちゃんの備忘録も兼ねています。

タッチに追従してViewを動かす

今までどうやったらいいかわからなかったのですが、意外に簡単でした。

activity_main.xml

<?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=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/HelloWorld"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView helloWorld = findViewById(R.id.HelloWorld);
helloWorld.setOnTouchListener(new moveOnTouchListener());

}

public static class moveOnTouchListener implements View.OnTouchListener {

private static float dX;
private static float dY;

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {


switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN :
dX = view.getX() - motionEvent.getRawX();
dY = view.getY() - motionEvent.getRawY();
break;
case MotionEvent.ACTION_MOVE :
view.setY(motionEvent.getRawY() + dY);
view.setX(motionEvent.getRawX() + dX);
break;
case MotionEvent.ACTION_UP :
break;
}

return true;
}

}
}