Example usage for android.view MotionEvent getActionMasked

List of usage examples for android.view MotionEvent getActionMasked

Introduction

In this page you can find the example usage for android.view MotionEvent getActionMasked.

Prototype

public final int getActionMasked() 

Source Link

Document

Return the masked action being performed, without pointer index information.

Usage

From source file:kr.selfcontrol.selflocklauncher.picker.HorizontalPicker.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isEnabled()) {
        return false;
    }/*from www  .  j av a  2 s.c o m*/

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(event);

    int action = event.getActionMasked();
    switch (action) {
    case MotionEvent.ACTION_MOVE:

        float currentMoveX = event.getX();

        int deltaMoveX = (int) (mLastDownEventX - currentMoveX);

        if (mScrollingX || (Math.abs(deltaMoveX) > mTouchSlop) && mValues != null && mValues.length > 0) {

            if (!mScrollingX) {
                deltaMoveX = 0;
                mPressedItem = -1;
                mScrollingX = true;
                stopMarqueeIfNeeded();
            }

            final int range = getScrollRange();

            if (overScrollBy(deltaMoveX, 0, getScrollX(), 0, range, 0, mOverscrollDistance, 0, true)) {
                mVelocityTracker.clear();
            }

            final float pulledToX = getScrollX() + deltaMoveX;
            if (pulledToX < 0) {
                mLeftEdgeEffect.onPull((float) deltaMoveX / getWidth());
                if (!mRightEdgeEffect.isFinished()) {
                    mRightEdgeEffect.onRelease();
                }
            } else if (pulledToX > range) {
                mRightEdgeEffect.onPull((float) deltaMoveX / getWidth());
                if (!mLeftEdgeEffect.isFinished()) {
                    mLeftEdgeEffect.onRelease();
                }
            }

            mLastDownEventX = currentMoveX;
            invalidate();

        }

        break;
    case MotionEvent.ACTION_DOWN:

        if (!mAdjustScrollerX.isFinished()) {
            mAdjustScrollerX.forceFinished(true);
        } else if (!mFlingScrollerX.isFinished()) {
            mFlingScrollerX.forceFinished(true);
        } else {
            mScrollingX = false;
        }

        mLastDownEventX = event.getX();

        if (!mScrollingX) {
            mPressedItem = getPositionFromTouch(event.getX());
        }
        invalidate();

        break;
    case MotionEvent.ACTION_UP:

        VelocityTracker velocityTracker = mVelocityTracker;
        velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
        int initialVelocityX = (int) velocityTracker.getXVelocity();

        if (mScrollingX && Math.abs(initialVelocityX) > mMinimumFlingVelocity) {
            flingX(initialVelocityX);
        } else if (mValues != null) {
            float positionX = event.getX();
            if (!mScrollingX) {

                int itemPos = getPositionOnScreen(positionX);
                int relativePos = itemPos - mSideItems;

                if (relativePos == 0) {
                    selectItem();
                } else {
                    smoothScrollBy(relativePos);
                }

            } else if (mScrollingX) {
                finishScrolling();
            }
        }

        mVelocityTracker.recycle();
        mVelocityTracker = null;

        if (mLeftEdgeEffect != null) {
            mLeftEdgeEffect.onRelease();
            mRightEdgeEffect.onRelease();
        }

    case MotionEvent.ACTION_CANCEL:
        mPressedItem = -1;
        invalidate();

        if (mLeftEdgeEffect != null) {
            mLeftEdgeEffect.onRelease();
            mRightEdgeEffect.onRelease();
        }

        break;
    }

    return true;
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java

@SuppressWarnings("deprecation")
@Override//from w  w w.  j a va2s.c o m
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring */
    final RelativeLayout widgetView;
    TextView labelTextView;
    TextView valueTextView;
    int widgetLayout;
    String[] splitString;
    OpenHABWidget openHABWidget = getItem(position);
    int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getWidth();
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidgetlist_groupitem;
        break;
    case TYPE_SECTIONSWITCH:
        widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem;
        break;
    case TYPE_SWITCH:
        widgetLayout = R.layout.openhabwidgetlist_switchitem;
        break;
    case TYPE_ROLLERSHUTTER:
        widgetLayout = R.layout.openhabwidgetlist_rollershutteritem;
        break;
    case TYPE_TEXT:
        widgetLayout = R.layout.openhabwidgetlist_textitem;
        break;
    case TYPE_SLIDER:
        widgetLayout = R.layout.openhabwidgetlist_slideritem;
        break;
    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;
    case TYPE_SELECTION:
        widgetLayout = R.layout.openhabwidgetlist_selectionitem;
        break;
    case TYPE_SETPOINT:
        widgetLayout = R.layout.openhabwidgetlist_setpointitem;
        break;
    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_VIDEO_MJPEG:
        widgetLayout = R.layout.openhabwidgetlist_videomjpegitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    case TYPE_COLOR:
        widgetLayout = R.layout.openhabwidgetlist_coloritem;
        break;
    default:
        widgetLayout = R.layout.openhabwidgetlist_genericitem;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }

    // Process the colour attributes
    Integer iconColor = openHABWidget.getIconColor();
    Integer labelColor = openHABWidget.getLabelColor();
    Integer valueColor = openHABWidget.getValueColor();

    // Process widgets icon image
    MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage);
    // Some of widgets, for example Frame doesnt' have an icon, so...
    if (widgetImage != null) {
        if (openHABWidget.getIcon() != null) {
            // This is needed to escape possible spaces and everything according to rfc2396
            String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png");
            //                Log.d(TAG, "Will try to load icon from " + iconUrl);
            // Now set image URL
            widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword);
            if (iconColor != null)
                widgetImage.setColorFilter(iconColor);
            else
                widgetImage.clearColorFilter();
        }
    }
    TextView defaultTextView = new TextView(widgetView.getContext());
    // Get TextView for widget label and set it's color
    labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel);
    // Change label color only for non-frame widgets
    if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) {
        Log.d(TAG, String.format("Setting label color to %d", labelColor));
        labelTextView.setTextColor(labelColor);
    } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME)
        labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    // Get TextView for widget value and set it's color
    valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue);
    if (valueColor != null && valueTextView != null) {
        Log.d(TAG, String.format("Setting value color to %d", valueColor));
        valueTextView.setTextColor(valueColor);
    } else if (valueTextView != null)
        valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    defaultTextView = null;
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        if (labelTextView != null) {
            labelTextView.setText(openHABWidget.getLabel());
            if (valueColor != null)
                labelTextView.setTextColor(valueColor);
        }
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_GROUP:
        if (labelTextView != null && valueTextView != null) {
            splitString = openHABWidget.getLabel().split("\\[|\\]");
            labelTextView.setText(splitString[0]);
            if (splitString.length > 1) { // We have some value
                valueTextView.setText(splitString[1]);
            } else {
                // This is needed to clean up cached TextViews
                valueTextView.setText("");
            }
        }
        break;
    case TYPE_SECTIONSWITCH:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (splitString.length > 1 && valueTextView != null) { // We have some value
            valueTextView.setText(splitString[1]);
        } else {
            // This is needed to clean up cached TextViews
            valueTextView.setText("");
        }
        RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup);
        // As we create buttons in this radio in runtime, we need to remove all
        // exiting buttons first
        sectionSwitchRadioGroup.removeAllViews();
        sectionSwitchRadioGroup.setTag(openHABWidget);
        Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator();
        while (sectionMappingIterator.hasNext()) {
            OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next();
            SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater
                    .from(sectionSwitchRadioGroup.getContext())
                    .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup,
                            false);
            segmentedControlButton.setText(widgetMapping.getLabel());
            segmentedControlButton.setTag(widgetMapping.getCommand());
            if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) {
                if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    segmentedControlButton.setChecked(true);
                } else {
                    segmentedControlButton.setChecked(false);
                }
            } else {
                segmentedControlButton.setChecked(false);
            }
            segmentedControlButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "Button clicked");
                    RadioGroup group = (RadioGroup) view.getParent();
                    if (group.getTag() != null) {
                        OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                        SegmentedControlButton selectedButton = (SegmentedControlButton) view;
                        if (selectedButton.getTag() != null) {
                            sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                        }
                    }
                }
            });
            sectionSwitchRadioGroup.addView(segmentedControlButton);
        }

        sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId);
                if (selectedButton != null) {
                    Log.d(TAG, "Selected " + selectedButton.getText());
                    Log.d(TAG, "Command = " + (String) selectedButton.getTag());
                    //                  radioWidget.getItem().sendCommand((String)selectedButton.getTag());
                    sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                }
            }
        });
        break;
    case TYPE_SWITCH:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch);
        if (openHABWidget.hasItem()) {
            if (openHABWidget.getItem().getStateAsBoolean()) {
                switchSwitch.setChecked(true);
            } else {
                switchSwitch.setChecked(false);
            }
        }
        switchSwitch.setTag(openHABWidget.getItem());
        switchSwitch.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                SwitchCompat switchSwitch = (SwitchCompat) v;
                OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    if (!switchSwitch.isChecked()) {
                        sendItemCommand(linkedItem, "ON");
                    } else {
                        sendItemCommand(linkedItem, "OFF");
                    }
                return false;
            }
        });
        break;
    case TYPE_COLOR:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up);
        ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down);
        ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color);
        colorUpButton.setTag(openHABWidget.getItem());
        colorDownButton.setTag(openHABWidget.getItem());
        colorColorButton.setTag(openHABWidget.getItem());
        colorUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "ON");
                return false;
            }
        });
        colorDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "OFF");
                return false;
            }
        });
        colorColorButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (colorItem != null) {
                    if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                        Log.d(TAG, "Time to launch color picker!");
                        ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(),
                                new OnColorChangedListener() {
                                    public void colorChanged(float[] hsv, View v) {
                                        Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
                                        String newColor = String.valueOf(hsv[0]) + ","
                                                + String.valueOf(hsv[1] * 100) + ","
                                                + String.valueOf(hsv[2] * 100);
                                        OpenHABItem colorItem = (OpenHABItem) v.getTag();
                                        sendItemCommand(colorItem, newColor);
                                    }
                                }, colorItem.getStateAsHSV());
                        colorDialog.setTag(colorItem);
                        colorDialog.show();
                    }
                }
                return false;
            }
        });
        break;
    case TYPE_ROLLERSHUTTER:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up);
        ImageButton rollershutterStopButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_stop);
        ImageButton rollershutterDownButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_down);
        rollershutterUpButton.setTag(openHABWidget.getItem());
        rollershutterStopButton.setTag(openHABWidget.getItem());
        rollershutterDownButton.setTag(openHABWidget.getItem());
        rollershutterUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "UP");
                return false;
            }
        });
        rollershutterStopButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "STOP");
                return false;
            }
        });
        rollershutterDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "DOWN");
                return false;
            }
        });
        break;
    case TYPE_TEXT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            if (splitString.length > 0) {
                labelTextView.setText(splitString[0]);
            } else {
                labelTextView.setText(openHABWidget.getLabel());
            }
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            } else {
                // If value is empty, hide TextView to fix vertical alignment of label
                valueTextView.setVisibility(View.GONE);
                valueTextView.setText("");
            }
        break;
    case TYPE_SLIDER:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar);
        if (openHABWidget.hasItem()) {
            sliderSeekBar.setTag(openHABWidget.getItem());
            sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue());
            sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress());
                    OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag();
                    //                     sliderItem.sendCommand(String.valueOf(seekBar.getProgress()));
                    if (sliderItem != null && seekBar != null)
                        sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress()));
                }
            });
            if (volumeUpWidget == null) {
                volumeUpWidget = sliderSeekBar;
                volumeDownWidget = sliderSeekBar;
            }
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false,
                openHABUsername, openHABPassword);
        //          ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams();
        //          float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight();
        //          imageLayoutParams.height = (int) (screenWidth/imageRatio);
        //          imageImage.setLayoutParams(imageLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        //Always clear the drawable so no images from recycled views appear
        chartImage.setImageDrawable(null);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem != null) {
            if (chartItem.getType().equals("GroupItem")) {
                chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            } else {
                chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            }
            if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) {
                chartUrl += "&service=" + openHABWidget.getService();
            }
        }
        Log.d(TAG, "Chart url = " + chartUrl);
        if (chartImage == null)
            Log.e(TAG, "chartImage == null !!!");
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        chartLayoutParams.height = (int) (screenWidth / 2);
        chartImage.setLayoutParams(chartLayoutParams);
        chartUrl += "&w=" + String.valueOf(screenWidth);
        chartUrl += "&h=" + String.valueOf(screenWidth / 2);
        chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.d(TAG, "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.d(TAG, "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_VIDEO_MJPEG:
        Log.d(TAG, "Video is mjpeg");
        ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage);
        MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername,
                this.openHABPassword, this.getContext());
        mjpegStreamer.setTargetImageView(mjpegImage);
        mjpegStreamer.start();
        if (!mjpegWidgetList.contains(mjpegStreamer))
            mjpegWidgetList.add(mjpegStreamer);
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(
                new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword));
        webWeb.getSettings().setJavaScriptEnabled(true);
        webWeb.loadUrl(openHABWidget.getUrl());
        break;
    case TYPE_SELECTION:
        int spinnerSelectedIndex = -1;
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner);
        selectionSpinner.setOnItemSelectedListener(null);
        ArrayList<String> spinnerArray = new ArrayList<String>();
        Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator();
        while (mappingIterator.hasNext()) {
            OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
            spinnerArray.add(openHABWidgetMapping.getLabel());
            if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null)
                if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    spinnerSelectedIndex = spinnerArray.size() - 1;
                }
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, spinnerArray);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectionSpinner.setAdapter(spinnerAdapter);
        selectionSpinner.setTag(openHABWidget);
        if (spinnerSelectedIndex >= 0) {
            Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex));
            selectionSpinner.setSelection(spinnerSelectedIndex);
        } else {
            Log.d(TAG, "Not setting spinner selected index");
        }
        selectionSpinner.post(new Runnable() {
            @Override
            public void run() {
                selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
                        Log.d(TAG, "Spinner item click on index " + index);
                        Spinner spinner = (Spinner) parent;
                        String selectedLabel = (String) spinner.getAdapter().getItem(index);
                        Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel);
                        OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag();
                        if (openHABWidget != null) {
                            Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel());
                            Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings()
                                    .iterator();
                            while (mappingIterator.hasNext()) {
                                OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
                                if (openHABWidgetMapping.getLabel().equals(selectedLabel)) {
                                    Log.d(TAG, "Spinner onItemSelected found match with "
                                            + openHABWidgetMapping.getCommand());
                                    if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() != null) {
                                        // Only send the command for selection of selected command will change the state
                                        if (!openHABWidget.getItem().getState()
                                                .equals(openHABWidgetMapping.getCommand())) {
                                            Log.d(TAG,
                                                    "Spinner onItemSelected selected label command != current item state");
                                            sendItemCommand(openHABWidget.getItem(),
                                                    openHABWidgetMapping.getCommand());
                                        }
                                    } else if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() == null) {
                                        Log.d(TAG,
                                                "Spinner onItemSelected selected label command and state == null");
                                        sendItemCommand(openHABWidget.getItem(),
                                                openHABWidgetMapping.getCommand());
                                    }
                                }
                            }
                        }
                        //               if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand()))
                        //                  sendItemCommand(openHABWidget.getItem(),
                        //                        openHABWidget.getMapping(index).getCommand());
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
            }
        });
        break;
    case TYPE_SETPOINT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            }
        Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus);
        Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus);
        setPointMinusButton.setTag(openHABWidget);
        setPointPlusButton.setTag(openHABWidget);
        setPointMinusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Minus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue - setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));

            }
        });
        setPointPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Plus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue + setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));
            }
        });
        if (volumeUpWidget == null) {
            volumeUpWidget = setPointPlusButton;
            volumeDownWidget = setPointMinusButton;
        }
        break;
    default:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

From source file:io.doist.datetimepicker.time.RadialTimePickerView.java

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (!mInputEnabled) {
        return true;
    }/*from w  ww. j  a  v  a  2s  . c o  m*/

    final int action = event.getActionMasked();
    if (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_UP
            || action == MotionEvent.ACTION_DOWN) {
        boolean forceSelection = false;
        boolean autoAdvance = false;

        if (action == MotionEvent.ACTION_DOWN) {
            // This is a new event stream, reset whether the value changed.
            mChangedDuringTouch = false;
        } else if (action == MotionEvent.ACTION_UP) {
            autoAdvance = true;

            // If we saw a down/up pair without the value changing, assume
            // this is a single-tap selection and force a change.
            if (!mChangedDuringTouch) {
                forceSelection = true;
            }
        }

        mChangedDuringTouch |= handleTouchInput(event.getX(), event.getY(), forceSelection, autoAdvance);
    }

    return true;
}

From source file:org.mariotaku.twidere.activity.support.ComposeActivity.java

@Override
public boolean onTouchEvent(final MotionEvent event) {
    switch (event.getActionMasked()) {
    case MotionEvent.ACTION_DOWN: {
        final Rect rect = new Rect();
        getWindow().getDecorView().getHitRect(rect);
        if (!rect.contains(Math.round(event.getX()), Math.round(event.getY()))) {
            onBackPressed();//from  w  ww .  j a  v a2s  . c  o  m
            return true;
        }
        break;
    }
    }
    return super.onTouchEvent(event);
}

From source file:com.hippo.widget.recyclerview.EasyRecyclerView.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }/*w  w  w .  ja  va  2  s  .com*/

    switch (ev.getActionMasked()) {
    case MotionEvent.ACTION_DOWN: {
        onTouchDown(ev);
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        onTouchMove(ev);
        break;
    }

    case MotionEvent.ACTION_UP: {
        onTouchUp(ev);
        break;
    }

    case MotionEvent.ACTION_CANCEL: {
        onTouchCancel();
        break;
    }
    }

    super.onTouchEvent(ev);

    return true;
}

From source file:info.bartowski.easteregg.MLand.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    L("touch: %s", ev);
    final int actionIndex = ev.getActionIndex();
    final float x = ev.getX(actionIndex);
    final float y = ev.getY(actionIndex);
    int playerIndex = (int) (getNumPlayers() * (x / getWidth()));
    if (mFlipped)
        playerIndex = getNumPlayers() - 1 - playerIndex;
    switch (ev.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_POINTER_DOWN:
        poke(playerIndex, x, y);/*from   www.j  av a  2  s . c  om*/
        return true;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
        unpoke(playerIndex);
        return true;
    }
    return false;
}

From source file:com.android.gallery3d.filtershow.FilterShowActivity.java

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (mHandlingSwipeButton) {
        int direction = CategoryView.HORIZONTAL;
        if (mHandledSwipeView instanceof CategoryView) {
            direction = ((CategoryView) mHandledSwipeView).getOrientation();
        }//from w  w  w .j a  v  a2  s.  c  o m
        if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) {
            float delta = ev.getY() - mSwipeStartY;
            float distance = mHandledSwipeView.getHeight();
            if (direction == CategoryView.VERTICAL) {
                delta = ev.getX() - mSwipeStartX;
                mHandledSwipeView.setTranslationX(delta);
                distance = mHandledSwipeView.getWidth();
            } else {
                mHandledSwipeView.setTranslationY(delta);
            }
            delta = Math.abs(delta);
            float transparency = Math.min(1, delta / distance);
            mHandledSwipeView.setAlpha(1.f - transparency);
            mHandledSwipeViewLastDelta = delta;
        }
        if (ev.getActionMasked() == MotionEvent.ACTION_CANCEL
                || ev.getActionMasked() == MotionEvent.ACTION_UP) {
            mHandledSwipeView.setTranslationX(0);
            mHandledSwipeView.setTranslationY(0);
            mHandledSwipeView.setAlpha(1.f);
            mHandlingSwipeButton = false;
            float distance = mHandledSwipeView.getHeight();
            if (direction == CategoryView.VERTICAL) {
                distance = mHandledSwipeView.getWidth();
            }
            if (mHandledSwipeViewLastDelta > distance) {
                ((SwipableView) mHandledSwipeView).delete();
            }
        }
        return true;
    }
    return super.dispatchTouchEvent(ev);
}

From source file:com.android.deskclock.alarms.AlarmActivity.java

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if (mAlarmHandled) {
        LogUtils.v(LOGTAG, "onTouch ignored: %s", motionEvent);
        return false;
    }//  ww w  . j av a2s  .com

    final int[] contentLocation = { 0, 0 };
    mContentView.getLocationOnScreen(contentLocation);

    final float x = motionEvent.getRawX() - contentLocation[0];
    final float y = motionEvent.getRawY() - contentLocation[1];

    final int alarmLeft = mAlarmButton.getLeft() + mAlarmButton.getPaddingLeft();
    final int alarmRight = mAlarmButton.getRight() - mAlarmButton.getPaddingRight();

    final float snoozeFraction, dismissFraction;
    if (mContentView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
        snoozeFraction = getFraction(alarmRight, mSnoozeButton.getLeft(), x);
        dismissFraction = getFraction(alarmLeft, mDismissButton.getRight(), x);
    } else {
        snoozeFraction = getFraction(alarmLeft, mSnoozeButton.getRight(), x);
        dismissFraction = getFraction(alarmRight, mDismissButton.getLeft(), x);
    }
    setAnimatedFractions(snoozeFraction, dismissFraction);

    switch (motionEvent.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
        LogUtils.v(LOGTAG, "onTouch started: %s", motionEvent);

        // Stop the pulse, allowing the last pulse to finish.
        mPulseAnimator.setRepeatCount(0);
        break;
    case MotionEvent.ACTION_UP:
        LogUtils.v(LOGTAG, "onTouch ended: %s", motionEvent);

        if (snoozeFraction == 1.0f) {
            snooze();
        } else if (dismissFraction == 1.0f) {
            dismiss();
        } else {
            if (snoozeFraction > 0.0f || dismissFraction > 0.0f) {
                // Animate back to the initial state.
                AnimatorUtils.reverse(mAlarmAnimator, mSnoozeAnimator, mDismissAnimator);
            } else if (mAlarmButton.getTop() <= y && y <= mAlarmButton.getBottom()) {
                // User touched the alarm button, hint the dismiss action
                hintDismiss();
            }

            // Restart the pulse.
            mPulseAnimator.setRepeatCount(ValueAnimator.INFINITE);
            if (!mPulseAnimator.isStarted()) {
                mPulseAnimator.start();
            }
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        resetAnimations();
        break;
    default:
        break;
    }

    return true;
}

From source file:com.esri.android.mapsapp.MapFragment.java

/**
 * Takes a MapView that has already been instantiated to show a WebMap,
 * completes its setup by setting various listeners and attributes, and sets
 * it as the activity's content view./*from  ww  w .j av  a 2s . co m*/
 * 
 * @param mapView
 */
private void setMapView(final MapView mapView) {

    mMapView = mapView;
    mMapView.setEsriLogoVisible(true);
    mMapView.enableWrapAround(true);
    mapView.setAllowRotationByPinch(true);

    // Creating an inflater
    mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Setting up the layout params for the searchview and searchresult
    // layout
    mlayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
            Gravity.LEFT | Gravity.TOP);
    int LEFT_MARGIN_SEARCH = 15;
    int RIGHT_MARGIN_SEARCH = 15;
    int BOTTOM_MARGIN_SEARCH = 0;
    mlayoutParams.setMargins(LEFT_MARGIN_SEARCH, TOP_MARGIN_SEARCH, RIGHT_MARGIN_SEARCH, BOTTOM_MARGIN_SEARCH);

    // Add the map to the layout
    mMapContainer.addView(mMapView, 0);

    // Set up floating action button
    setClickListenerForFloatingActionButton();

    // Displaying the searchbox layout
    showSearchBoxLayout();

    mMapView.setOnPinchListener(new OnPinchListener() {

        /**
         * Default value
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void postPointersDown(float x1, float y1, float x2, float y2, double factor) {
        }

        @Override
        public void postPointersMove(float x1, float y1, float x2, float y2, double factor) {
        }

        @Override
        public void postPointersUp(float x1, float y1, float x2, float y2, double factor) {
        }

        @Override
        public void prePointersDown(float x1, float y1, float x2, float y2, double factor) {
        }

        @Override
        public void prePointersMove(float x1, float y1, float x2, float y2, double factor) {
            if (mMapView.getRotationAngle() > 5 || mMapView.getRotationAngle() < -5) {
                mCompass.setVisibility(View.VISIBLE);
                mCompass.sensorManager.unregisterListener(mCompass.sensorEventListener);
                mCompass.setRotationAngle(mMapView.getRotationAngle());
            }
        }

        @Override
        public void prePointersUp(float x1, float y1, float x2, float y2, double factor) {
        }

    });

    // Setup listener for map initialized
    mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void onStatusChanged(Object source, STATUS status) {

            if (source == mMapView && status == STATUS.INITIALIZED) {

                mapSpatialReference = mMapView.getSpatialReference();

                if (mMapViewState == null) {
                    // Starting location tracking will cause zoom to My
                    // Location
                    startLocationTracking();
                } else {
                    mMapView.restoreState(mMapViewState);
                }
                // add search and routing layers
                addGraphicLayers();
            }
        }
    });

    // Setup use of magnifier on a long press on the map
    mMapView.setShowMagnifierOnLongPress(true);
    mLongPressEvent = null;

    // Setup OnTouchListener to detect and act on long-press
    mMapView.setOnTouchListener(new MapOnTouchListener(getActivity(), mMapView) {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                // Start of a new gesture. Make sure mLongPressEvent is
                // cleared.
                mLongPressEvent = null;
            }
            return super.onTouch(v, event);
        }

        @Override
        public void onLongPress(MotionEvent point) {
            // Set mLongPressEvent to indicate we are processing a
            // long-press
            mLongPressEvent = point;
            super.onLongPress(point);

        }

        @Override
        public boolean onDragPointerUp(MotionEvent from, final MotionEvent to) {
            if (mLongPressEvent != null) {
                // This is the end of a long-press that will have displayed
                // the
                // magnifier.
                // Perform reverse-geocoding of the point that was pressed
                Point mapPoint = mMapView.toMapPoint(to.getX(), to.getY());
                ReverseGeocodingAsyncTask reverseGeocodeTask = new ReverseGeocodingAsyncTask();
                reverseGeocodeTask.execute(mapPoint);
                mPendingTask = reverseGeocodeTask;

                mLongPressEvent = null;
                // Remove any previous graphics
                resetGraphicsLayers();
            }
            return super.onDragPointerUp(from, to);
        }

    });

}

From source file:com.grottworkshop.gwsswipelayout.SwipeLayout.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {

    if (!isEnabled() || !isEnabledInAdapterView()) {
        return true;
    }/*from   w w  w  .  j  a v a 2  s. c o  m*/

    if (!isSwipeEnabled()) {
        return false;
    }

    for (SwipeDenier denier : mSwipeDeniers) {
        if (denier != null && denier.shouldDenySwipe(ev)) {
            return false;
        }
    }
    //
    //if a child wants to handle the touch event,
    //then let it do it.
    //
    int action = ev.getActionMasked();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        Status status = getOpenStatus();
        if (status == Status.Close) {
            mTouchConsumedByChild = childNeedHandleTouchEvent(getSurfaceView(), ev) != null;
        } else if (status == Status.Open) {
            mTouchConsumedByChild = childNeedHandleTouchEvent(getBottomView(), ev) != null;
        }
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        mTouchConsumedByChild = false;
    }

    return !mTouchConsumedByChild && mDragHelper.shouldInterceptTouchEvent(ev);
}