onTouch()方法未显示任何用法

时间:2018-12-14 10:56:31

标签: android

我正在尝试从图像中获取像素颜色,以便可以匹配颜色并从片段开始活动。有人可以帮我吗?Here's my code with information

1 个答案:

答案 0 :(得分:0)

请检查以下代码以获取更多详细信息。

public class SampleFragment extends Fragment implements View.OnTouchListener {

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_explore, container, false);
            view.setOnTouchListener(this);
            return view;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Rect rectangle = new Rect();
            Window window = Objects.requireNonNull(getActivity()).getWindow();
            window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
            int statusBarHeight = rectangle.top;
            int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
            int titleBarHeight = contentViewTop - statusBarHeight;


            final int action = event.getAction();

            final int evX = (int) event.getX();
            final int evY = (int) event.getY();

            switch (action) {
                case MotionEvent.ACTION_UP:
                    int touchColor = getHotspotColor(R.id.image_areas, evX, evY - statusBarHeight);
                    if (touchColor == Color.parseColor("ff9933")) {
                        /*Intent intent = new Intent(getActivity(), IndiaFragment.class);
                        startActivity(intent);*/
                        //TODO: IndiaFragment.class should be activity class not fragment
                    }
                    break;
            }
            return true;
        }

        public int getHotspotColor(int hotspotId, int x, int y) {
            ImageView img = Objects.requireNonNull(getView()).findViewById(hotspotId);
            img.setDrawingCacheEnabled(true);
            Bitmap hotspot = Bitmap.createBitmap(img.getDrawingCache());
            img.setDrawingCacheEnabled(false);
            return hotspot.getPixel(x, y);
        }
    }

如果这不起作用,则发布整个代码。