繁体   English   中英

在ImageView外部触摸时,Android应用程序崩溃

[英]Android app crashes when touched outside the ImageView

当我触摸ImageView时,它会显示图像中的颜色,但当我触摸图像外,应用程序崩溃了。

这是我的xml代码:

 <ImageView
    android:id="@+id/colorimage"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:src="@drawable/color" />

<ImageView
    android:id="@+id/displaycolor"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/colorimage"/>

这是主要代码:

 mImageView.setDrawingCacheEnabled(true);
    mImageView.buildDrawingCache(true);

    mImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){
                Bitmap bitmap = mImageView.getDrawingCache();

               int pixel = bitmap.getPixel((int)event.getX(), (int)event.getY());

                int r = Color.red(pixel);
                int g = Color.green(pixel);
                int b = Color.blue(pixel);

                display.setBackgroundColor(Color.rgb(r , g , b));

            }

            return true;
        }
    });

Logcat错误消息: 错误日志

将行if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)更改为:

if(v.getId() == R.id.colorimage){
    if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
       {........}
}

触摸侦听器已设置为整个活动而不是特定视图,并且位图操作无法在除此之外的其他视图上完成,因此视图因此崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM