【问题标题】:How to move an image to touch location?如何将图像移动到触摸位置?
【发布时间】:2019-08-01 03:58:15
【问题描述】:

我正在尝试制作一个用户可以在其中移动角色的开始屏幕(图片)。

我写了一些我认为是正确的代码,但是当我运行应用程序时它似乎没有做任何事情。

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;
        }
    };

当我运行应用程序时,图像不会在触摸时移动或根本不会移动。

【问题讨论】:

标签: java android


【解决方案1】:

在布局中添加触摸侦听器而不是图像视图 例子: 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

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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多