安卓图像视图的触摸事件

5

我正在创建一个安卓应用程序。 这里有一个ImageView。 我的目标是在手指在图片上移动时从数据库中获取下一张图片。

float nPicturePositionM = 0;

public boolean onTouch(View v, MotionEvent event) {
    boolean aHandledL = false;
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        float nNewPicturePosL = event.getX();
        if (nPicturePositionM < nNewPicturePosL) {
            nPicturePositionM = nNewPicturePosL;
            GetPictures(true);
        } else {
            nPicturePositionM = nNewPicturePosL;
            GetPictures(false);
        }
        aHandledL = true;
    }

    return aHandledL;

    //return false;
}

如何使用触摸事件来处理图片滑动,就像在画廊中一样。
2个回答

13

首先在你的xml中声明一个ImageView:

<ImageView
    android:id="@+id/imageview1"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="45dp"
    android:layout_centerHorizontal="true" />

然后在你的活动中初始化该组件:

private ImageView image1;

在onCreate方法中:

this.image1= (ImageView)this.findViewById(R.id.imageview1);
this.image1.setImageResource(R.drawable.NAMEOFIMAGE);
下一步是检测图片是否被“点击”。然后,您可以使用在线数据库或SQLite数据库来保存图像或图像路径,具体的数据库部分取决于您选择的路线需要从头开始教导的大部分内容:
       this.image1.setOnClickListener(new View.OnClickListener() {        
        @Override
           public void onClick(View view) {
            if (view == findViewById(R.id.imageview1)) {     
                         //PUT IN CODE HERE TO GET NEXT IMAGE
            }
            }
        });

希望这能帮到你,让我知道进展如何 :)


1
我该如何使用触摸事件来处理它?图片应该像在画廊中一样滑动。 - user1618951
我不太确定,可能与刷新率有关。我会调查一下并回复你。 - Ushal Naidoo
我想根据左右滑动获取下一张和上一张图片。你能帮我解决如何实现吗? - user1618951
预览是什么意思?您想显示主要图像并根据滑动方向显示下一个图像的迷你缩略图吗?如果是这样,请按照与主要图像相同的方式将Imageview添加到XML中,并根据数据库中的下一个图像加载图像到该imageview中。 - Ushal Naidoo
这只是一个拼写错误。在“创建事件”中,我展示了一张图片,当我向右滑动时,希望从数据库中看到下一张图片,当我向左滑动时,希望从数据库中看到上一张图片。 - user1618951
显示剩余3条评论

0

你需要使用来自数据库的图像数组,并根据触摸设置它们...就像这样。

img.setOnTouchListener(new OnTouchListener() 
        {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) 
            {
                    img.setImageURI(uri[pos]);
                    pos++;
                    return false;
            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接