首页 > 解决方案 > 每当单击按钮时,多次在屏幕上放置相同的图像

问题描述

当用户单击按钮时,相同的图像将在多个位置一次又一次地显示。我正在使用触摸监听器来移动图像。这是有效的,但我无法使用相同的图像视图或 for 循环创建多个图像,请帮助。这是我要多次创建的图像 这是我的 xml

      <?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:orientation="vertical"
android:id="@+id/main_html"
tools:context="com.incubers.signondoc.ui.HtmlActivity">

<Button
    android:id="@+id/save_edited"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"
    style="?android:button"
    android:text="@string/hint_save" />


<com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/viewpdfHtml"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageSign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/no_connection" />

</com.github.barteksc.pdfviewer.PDFView>`

这是我用于移动图像和其他代码的 ontouchlistener

ImageView imageView;
 ViewGroup mainLayout;
 private View.OnTouchListener onTouchListener() {
    return (view, event) -> {
        final int x = (int) event.getRawX();
        final int y = (int) event.getRawY();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {

            case MotionEvent.ACTION_DOWN:
                RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
                        view.getLayoutParams();
                xDelta = x - lParams.leftMargin;
                yDelta = y - lParams.topMargin;
                break;

            case MotionEvent.ACTION_UP:
                float xD = event.getX();
                float yD = event.getY();
                DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
                float   XDis = displayMetrics.xdpi;
                float  YDis = displayMetrics.ydpi;
                finalX = xD/XDis*100;
                finalY  = yD/YDis*100;

                break;
            case MotionEvent.ACTION_MOVE:
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();
                layoutParams.leftMargin = x - xDelta;
                layoutParams.topMargin = y - yDelta;
                layoutParams.rightMargin = 0;
                layoutParams.bottomMargin = 0;
                view.setLayoutParams(layoutParams);

                break;

        }
        mainLayout.invalidate();
        return true;
    };
}

这是应该在点击时显示图像的按钮

  buttonSign.setOnClickListener(view ->{

            }

        });

标签: javaandroiddynamicimageview

解决方案


您需要动态创建 ImageView 以使其正常工作,这可能会对您有所帮助:

在循环内动态创建 ImageView


推荐阅读