[英]How to move an image to touch location?
I'm trying to make a start screen where the user can move a character around (Image). 我正在尝试制作一个开始屏幕,用户可以在其中移动字符(图像)。
I've written some code that I think is correct, but it doesn't seem to do anything when I run the app. 我写了一些我认为是正确的代码,但是当我运行该应用程序时,它似乎没有任何作用。
public class MainActivity extends AppCompatActivity {
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.imageView);
image.setOnTouchListener(touchListener);
}
View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN){
image.setX(event.getX());
image.setY(event.getY());
return true;
}
return false;
}
};
When I run the app the image doesn't move on touch or at all. 当我运行该应用程序时,触摸或完全不移动图像。
Instead of image view add touch listener to the layout Example: activity_main.xml 代替图像视图,将触摸侦听器添加到布局示例:activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/constrainLayout"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
constrainLayout.setOnTouchListener(touchListener)
}
var touchListener: OnTouchListener = OnTouchListener { v, event ->
val action = event.action
imageView.x = event.x
imageView.y = event.y
false
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.