Example usage for android.view KeyEvent KEYCODE_ENTER

List of usage examples for android.view KeyEvent KEYCODE_ENTER

Introduction

In this page you can find the example usage for android.view KeyEvent KEYCODE_ENTER.

Prototype

int KEYCODE_ENTER

To view the source code for android.view KeyEvent KEYCODE_ENTER.

Click Source Link

Document

Key code constant: Enter key.

Usage

From source file:com.wdullaer.materialdatetimepicker.time.TimePickerView.java

/**
 * For keyboard mode, processes key events.
 * @param keyCode the pressed key.//from www. j av  a 2s .  c  o m
 * @return true if the key was successfully processed, false otherwise.
 */
private boolean processKeyUp(int keyCode) {
    if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
        //            if(isCancelable()) dismiss();
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_TAB) {
        if (mInKbMode) {
            if (isTypedTimeFullyLegal()) {
                finishKbMode(true);
            }
            return true;
        }
    } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
        if (mInKbMode) {
            if (!isTypedTimeFullyLegal()) {
                return true;
            }
            finishKbMode(false);
        }
        if (mCallback != null) {
            mCallback.onTimeSet(mTimePicker, mTimePicker.getHours(), mTimePicker.getMinutes(),
                    mTimePicker.getSeconds());
        }
        //            dismiss();
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_DEL) {
        if (mInKbMode) {
            if (!mTypedTimes.isEmpty()) {
                int deleted = deleteLastTypedKey();
                String deletedKeyStr;
                if (deleted == getAmOrPmKeyCode(AM)) {
                    deletedKeyStr = mAmText;
                } else if (deleted == getAmOrPmKeyCode(PM)) {
                    deletedKeyStr = mPmText;
                } else {
                    deletedKeyStr = String.format("%d", getValFromKeyCode(deleted));
                }
                Utils.tryAccessibilityAnnounce(mTimePicker, String.format(mDeletedKeyFormat, deletedKeyStr));
                updateDisplay(true);
            }
        }
    } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 || keyCode == KeyEvent.KEYCODE_2
            || keyCode == KeyEvent.KEYCODE_3 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
            || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 || keyCode == KeyEvent.KEYCODE_8
            || keyCode == KeyEvent.KEYCODE_9
            || (!mIs24HourMode && (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
        if (!mInKbMode) {
            if (mTimePicker == null) {
                // Something's wrong, because time picker should definitely not be null.
                Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
                return true;
            }
            mTypedTimes.clear();
            tryStartingKbMode(keyCode);
            return true;
        }
        // We're already in keyboard mode.
        if (addKeyIfLegal(keyCode)) {
            updateDisplay(false);
        }
        return true;
    }
    return false;
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

/**
 * Hook up buttons, lists, and edittext with functionality.
 *//* w w  w.  j av a  2s.  c o m*/
private void createView() {

    // Temp-create either Spinner or List based upon the Display
    createList();

    mAddPanel = findViewById(R.id.add_panel);
    mEditText = (AutoCompleteTextView) findViewById(R.id.autocomplete_add_item);

    fillAutoCompleteTextViewAdapter(mEditText);
    mEditText.setThreshold(1);
    mEditText.setOnKeyListener(new OnKeyListener() {

        private int mLastKeyAction = KeyEvent.ACTION_UP;

        public boolean onKey(View v, int keyCode, KeyEvent key) {
            // Shortcut: Instead of pressing the button,
            // one can also press the "Enter" key.
            if (debug) {
                Log.i(TAG, "Key action: " + key.getAction());
            }
            if (debug) {
                Log.i(TAG, "Key code: " + keyCode);
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER) {

                if (mEditText.isPopupShowing()) {
                    mEditText.performCompletion();
                }

                // long key press might cause call of duplicate onKey events
                // with ACTION_DOWN
                // this would result in inserting an item and showing the
                // pick list

                if (key.getAction() == KeyEvent.ACTION_DOWN && mLastKeyAction == KeyEvent.ACTION_UP) {
                    insertNewItem();
                }

                mLastKeyAction = key.getAction();
                return true;
            }
            return false;
        }
    });
    mEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (mItemsView.mMode == MODE_ADD_ITEMS) {
                // small optimization: Only care about updating
                // the button label on each key pressed if we
                // are in "add items" mode.
                updateButton();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

    });

    mButton = (Button) findViewById(R.id.button_add_item);
    mButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            insertNewItem();
        }
    });
    mButton.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (PreferenceActivity.getAddForBarcode(getApplicationContext()) == false) {
                if (debug) {
                    Log.v(TAG, "barcode scanner on add button long click disabled");
                }
                return false;
            }

            Intent intent = new Intent();
            intent.setData(mListUri);
            intent.setClassName("org.openintents.barcodescanner",
                    "org.openintents.barcodescanner.BarcodeScanner");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            try {
                startActivityForResult(intent, REQUEST_CODE_CATEGORY_ALTERNATIVE);
            } catch (ActivityNotFoundException e) {
                if (debug) {
                    Log.v(TAG, "barcode scanner not found");
                }
                showDialog(DIALOG_GET_FROM_MARKET);
                return false;
            }

            // Instead of calling the class of barcode
            // scanner directly, a more generic approach would
            // be to use a general activity picker.
            //
            // TODO: Implement onActivityResult.
            // Problem: User has to pick activity every time.
            // Choice should be storeable in Stettings.
            // Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // intent.setData(mListUri);
            // intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            //
            // Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
            // pickIntent.putExtra(Intent.EXTRA_INTENT, intent);
            // pickIntent.putExtra(Intent.EXTRA_TITLE,
            // getText(R.string.title_select_item_from));
            // try {
            // startActivityForResult(pickIntent,
            // REQUEST_CODE_CATEGORY_ALTERNATIVE);
            // } catch (ActivityNotFoundException e) {
            // Log.v(TAG, "barcode scanner not found");
            // return false;
            // }
            return true;
        }
    });

    mLayoutParamsItems = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    mToastBar = (ActionableToastBar) findViewById(R.id.toast_bar);

    mItemsView = (ShoppingItemsView) findViewById(R.id.list_items);
    mItemsView.setThemedBackground(findViewById(R.id.background));
    mItemsView.setCustomClickListener(this);
    mItemsView.setToastBar(mToastBar);
    mItemsView.initTotals();

    mItemsView.setItemsCanFocus(true);
    mItemsView.setDragListener(new DragListener() {

        @Override
        public void drag(int from, int to) {
            if (debug) {
                Log.v("DRAG", "" + from + "/" + to);
            }

        }
    });
    mItemsView.setDropListener(new DropListener() {

        @Override
        public void drop(int from, int to) {
            if (debug) {
                Log.v("DRAG", "" + from + "/" + to);
            }

        }
    });

    mItemsView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView parent, View v, int pos, long id) {
            Cursor c = (Cursor) parent.getItemAtPosition(pos);
            onCustomClick(c, pos, EditItemDialog.FieldType.ITEMNAME, v);
            // DO NOT CLOSE THIS CURSOR - IT IS A MANAGED ONE.
            // ---- c.close();
        }

    });

    mItemsView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

        public void onCreateContextMenu(ContextMenu contextmenu, View view, ContextMenuInfo info) {
            contextmenu.add(0, MENU_EDIT_ITEM, 0, R.string.menu_edit_item).setShortcut('1', 'e');
            contextmenu.add(0, MENU_MARK_ITEM, 0, R.string.menu_mark_item).setShortcut('2', 'm');
            contextmenu.add(0, MENU_ITEM_STORES, 0, R.string.menu_item_stores).setShortcut('3', 's');
            contextmenu.add(0, MENU_REMOVE_ITEM_FROM_LIST, 0, R.string.menu_remove_item).setShortcut('4', 'r');
            contextmenu.add(0, MENU_COPY_ITEM, 0, R.string.menu_copy_item).setShortcut('5', 'c');
            contextmenu.add(0, MENU_DELETE_ITEM, 0, R.string.menu_delete_item).setShortcut('6', 'd');
            contextmenu.add(0, MENU_MOVE_ITEM, 0, R.string.menu_move_item).setShortcut('7', 'l');
        }

    });
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Helper to send a character to the editor as raw key events.
 *//*from ww  w  .  j a v  a  2 s  .c  o m*/
private void sendKey(int keyCode) {
    switch (keyCode) {
    case '\n':
        keyDownUp(KeyEvent.KEYCODE_ENTER);
        break;
    default:
        if (keyCode >= '0' && keyCode <= '9') {
            keyDownUp(keyCode - '0' + KeyEvent.KEYCODE_0);
        } else {
            ic.commitText(String.valueOf((char) keyCode), 1);
            if (shouldInsertSpace) {
                ic.commitText(" ", 1);
                shouldInsertSpace = false;
            }

        }
        break;
    }
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

private void addInterfaceListeners() {

    final OnMapClickListener onMapClickListener = new OnMapClickListener() {
        @Override/*from w  w  w .  ja v  a  2s  . c  o m*/
        public void onMapClick(LatLng latlng) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);

            if (mTbStartLocation.hasFocus()) {
                setMarker(true, latlng, true);
            } else {
                setMarker(false, latlng, true);
            }
        }
    };
    mMap.setOnMapClickListener(onMapClickListener);

    OnMarkerDragListener onMarkerDragListener = new OnMarkerDragListener() {

        @Override
        public void onMarkerDrag(Marker marker) {
        }

        @Override
        public void onMarkerDragEnd(Marker marker) {
            LatLng markerLatlng = marker.getPosition();

            if (((mOTPApp.getSelectedServer() != null) && LocationUtil.checkPointInBoundingBox(markerLatlng,
                    mOTPApp.getSelectedServer(), OTPApp.CHECK_BOUNDS_ACCEPTABLE_ERROR))
                    || (mOTPApp.getSelectedServer() == null)) {
                if ((mStartMarker != null) && (marker.hashCode() == mStartMarker.hashCode())) {
                    if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_INTELLIGENT_MARKERS, true)) {
                        updateMarkerPosition(markerLatlng, true);
                    } else {
                        mIsStartLocationGeocodingCompleted = true;
                        removeFocus(true);
                        setMarker(true, markerLatlng, false);
                    }
                    mStartMarkerPosition = markerLatlng;
                } else if ((mEndMarker != null) && (marker.hashCode() == mEndMarker.hashCode())) {
                    if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_INTELLIGENT_MARKERS, true)) {
                        updateMarkerPosition(markerLatlng, false);
                    } else {
                        mIsEndLocationGeocodingCompleted = true;
                        removeFocus(false);
                        setMarker(false, markerLatlng, false);
                    }
                    mEndMarkerPosition = markerLatlng;
                }
            } else {

                if ((mStartMarker != null) && (marker.hashCode() == mStartMarker.hashCode())) {
                    marker.setPosition(mStartMarkerPosition);
                } else {
                    marker.setPosition(mEndMarkerPosition);
                }
                Toast.makeText(mApplicationContext,
                        mApplicationContext.getResources().getString(
                                R.string.toast_map_markers_marker_out_of_boundaries),
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onMarkerDragStart(Marker marker) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);
        }
    };
    mMap.setOnMarkerDragListener(onMarkerDragListener);

    OnMapLongClickListener onMapLongClickListener = new OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latlng) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);

            final LatLng latLngFinal = latlng;
            final CharSequence[] items = {
                    mApplicationContext.getResources()
                            .getString(R.string.point_type_selector_start_marker_option),
                    mApplicationContext.getResources()
                            .getString(R.string.point_type_selector_end_marker_option) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.point_type_selector_title));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    if (item == 0) {
                        setMarker(true, latLngFinal, true);
                    } else {
                        setMarker(false, latLngFinal, true);
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    };
    mMap.setOnMapLongClickListener(onMapLongClickListener);

    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    };
    mBtnHandle.setOnClickListener(onClickListener);

    OnInfoWindowClickListener onInfoWindowClickListener = new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker modeMarker) {
            saveOTPBundle();
            OTPBundle otpBundle = getFragmentListener().getOTPBundle();
            Matcher matcher = Pattern.compile("\\d+").matcher(modeMarker.getTitle());
            if (matcher.find()) {
                String numberString = modeMarker.getTitle().substring(0, matcher.end());
                //Step indexes shown to the user are in a scale starting by 1 but instructions steps internally start by 0
                int currentStepIndex = Integer.parseInt(numberString) - 1;
                otpBundle.setCurrentStepIndex(currentStepIndex);
                otpBundle.setFromInfoWindow(true);
                getFragmentListener().setOTPBundle(otpBundle);
                getFragmentListener().onSwitchedToDirectionFragment();
            }

        }
    };
    mMap.setOnInfoWindowClickListener(onInfoWindowClickListener);

    DrawerListener dl = new DrawerListener() {
        @Override
        public void onDrawerStateChanged(int arg0) {
        }

        @Override
        public void onDrawerSlide(View arg0, float arg1) {

            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);
        }

        @Override
        public void onDrawerOpened(View arg0) {
        }

        @Override
        public void onDrawerClosed(View arg0) {
        }
    };
    mDrawerLayout.setDrawerListener(dl);

    OnTouchListener otlStart = new RightDrawableOnTouchListener(mTbStartLocation) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            final CharSequence[] items = {
                    getResources().getString(R.string.text_box_dialog_location_type_current_location),
                    getResources().getString(R.string.text_box_dialog_location_type_contact),
                    getResources().getString(R.string.text_box_dialog_location_type_map_point) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.text_box_dialog_choose_location_type_start));
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals(getResources()
                            .getString(R.string.text_box_dialog_location_type_current_location))) {
                        LatLng mCurrentLatLng = getLastLocation();
                        if (mCurrentLatLng != null) {
                            SharedPreferences.Editor prefsEditor = mPrefs.edit();
                            setTextBoxLocation(getResources().getString(R.string.text_box_my_location), true);
                            prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true);

                            if (mStartMarker != null) {
                                mStartMarker.remove();
                                mStartMarker = null;
                            }

                            prefsEditor.commit();
                        } else {
                            Toast.makeText(MainFragment.this.mApplicationContext,
                                    mApplicationContext.getResources()
                                            .getString(R.string.toast_tripplanner_current_location_error),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else if (items[item]
                            .equals(getResources().getString(R.string.text_box_dialog_location_type_contact))) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE);
                        ((MyActivity) MainFragment.this.getActivity()).setButtonStartLocation(true);

                        MainFragment.this.getActivity().startActivityForResult(intent,
                                OTPApp.CHOOSE_CONTACT_REQUEST_CODE);

                    } else { // Point on Map
                        if (mStartMarker != null) {
                            updateMarkerPosition(mStartMarker.getPosition(), true);
                        } else {
                            setTextBoxLocation("", true);
                            mTbStartLocation
                                    .setHint(getResources().getString(R.string.text_box_need_to_place_marker));
                            mTbStartLocation.requestFocus();
                        }
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

    };

    mTbStartLocation.setOnTouchListener(otlStart);

    OnTouchListener otlEnd = new RightDrawableOnTouchListener(mTbEndLocation) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            final CharSequence[] items = {
                    getResources().getString(R.string.text_box_dialog_location_type_current_location),
                    getResources().getString(R.string.text_box_dialog_location_type_contact),
                    getResources().getString(R.string.text_box_dialog_location_type_map_point) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.text_box_dialog_choose_location_type_end));
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals(getResources()
                            .getString(R.string.text_box_dialog_location_type_current_location))) {
                        LatLng mCurrentLatLng = getLastLocation();
                        if (mCurrentLatLng != null) {
                            SharedPreferences.Editor prefsEditor = mPrefs.edit();
                            setTextBoxLocation(getResources().getString(R.string.text_box_my_location), false);
                            prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, true);

                            if (mEndMarker != null) {
                                mEndMarker.remove();
                                mEndMarker = null;
                            }

                            prefsEditor.commit();
                        } else {
                            Toast.makeText(MainFragment.this.mApplicationContext,
                                    mApplicationContext.getResources()
                                            .getString(R.string.toast_tripplanner_current_location_error),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else if (items[item]
                            .equals(getResources().getString(R.string.text_box_dialog_location_type_contact))) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE);
                        ((MyActivity) MainFragment.this.getActivity()).setButtonStartLocation(false);

                        MainFragment.this.getActivity().startActivityForResult(intent,
                                OTPApp.CHOOSE_CONTACT_REQUEST_CODE);

                    } else { // Point on Map
                        if (mEndMarker != null) {
                            updateMarkerPosition(mEndMarker.getPosition(), false);
                        } else {
                            setTextBoxLocation("", false);
                            mTbEndLocation
                                    .setHint(getResources().getString(R.string.text_box_need_to_place_marker));
                            mTbEndLocation.requestFocus();
                        }
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

    };

    mTbEndLocation.setOnTouchListener(otlEnd);

    mBtnPlanTrip.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            processRequestTrip();
        }
    });

    OnFocusChangeListener tbLocationOnFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            if (hasFocus) {
                mMap.setOnMapClickListener(onMapClickListener);
            }

            TextView tv = (TextView) v;
            if (!hasFocus) {
                CharSequence tvCharSequence = tv.getText();

                if (tvCharSequence != null) {
                    String text = tvCharSequence.toString();

                    if (!TextUtils.isEmpty(text)) {
                        if (v.getId() == R.id.tbStartLocation && !mIsStartLocationGeocodingCompleted
                                && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true)) {
                            processAddress(true, text, false);
                        } else if (v.getId() == R.id.tbEndLocation && !mIsEndLocationGeocodingCompleted
                                && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, true)) {
                            processAddress(false, text, false);
                        }
                    } else {
                        if (v.getId() == R.id.tbStartLocation) {
                            tv.setHint(getResources().getString(R.string.text_box_start_location_hint));
                        } else if (v.getId() == R.id.tbEndLocation) {
                            tv.setHint(getResources().getString(R.string.text_box_end_location_hint));
                        }
                    }
                } else {
                    Log.w(OTPApp.TAG,
                            "Focus has changed, but was not possible to obtain start/end" + " textbox text");
                }
            }
        }
    };
    mTbStartLocation.setOnFocusChangeListener(tbLocationOnFocusChangeListener);
    mTbEndLocation.setOnFocusChangeListener(tbLocationOnFocusChangeListener);

    TextWatcher textWatcherStart = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mIsStartLocationChangedByUser) {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, false);
                prefsEditor.commit();
                mIsStartLocationGeocodingCompleted = false;
            } else {
                mIsStartLocationChangedByUser = true;
            }
        }
    };

    TextWatcher textWatcherEnd = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mIsEndLocationChangedByUser) {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, false);
                prefsEditor.commit();
                mIsEndLocationGeocodingCompleted = false;
            } else {
                mIsEndLocationChangedByUser = true;
            }
        }
    };

    mTbStartLocation.addTextChangedListener(textWatcherStart);
    mTbEndLocation.addTextChangedListener(textWatcherEnd);

    OnEditorActionListener tbLocationOnEditorActionListener = new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (v.getId() == R.id.tbStartLocation) {
                if (actionId == EditorInfo.IME_ACTION_NEXT
                        || (event != null && event.getAction() == KeyEvent.ACTION_DOWN
                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if (!mIsStartLocationGeocodingCompleted
                            && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true)) {
                        CharSequence tvCharSequence = v.getText();
                        if (tvCharSequence != null) {
                            processAddress(true, tvCharSequence.toString(), false);
                        } else {
                            Log.w(OTPApp.TAG, "User switched to next input, but was not possible to"
                                    + "obtain start/end textbox text");
                        }
                    }
                }
            } else if (v.getId() == R.id.tbEndLocation) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getAction() == KeyEvent.ACTION_DOWN
                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    processRequestTrip();
                }
            }
            return false;
        }
    };

    mTbStartLocation.setOnEditorActionListener(tbLocationOnEditorActionListener);
    mTbEndLocation.setOnEditorActionListener(tbLocationOnEditorActionListener);

    OnClickListener oclDisplayDirection = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            saveOTPBundle();
            getFragmentListener().onSwitchedToDirectionFragment();
        }
    };
    mBtnDisplayDirection.setOnClickListener(oclDisplayDirection);

    // Do NOT show direction icon if there is no direction yet
    toggleItinerarySelectionSpinner(!getFragmentListener().getCurrentItinerary().isEmpty());

    OnClickListener oclMyLocation = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            LatLng mCurrentLatLng = getLastLocation();

            if (mCurrentLatLng == null) {
                Toast.makeText(mApplicationContext, mApplicationContext.getResources()
                        .getString(R.string.toast_tripplanner_current_location_error), Toast.LENGTH_LONG)
                        .show();
            } else {
                if (mMap.getCameraPosition().zoom < OTPApp.defaultMyLocationZoomLevel) {
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng,
                            OTPApp.defaultMyLocationZoomLevel));
                } else {
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(getLastLocation()));
                }
            }
        }
    };
    mBtnMyLocation.setOnClickListener(oclMyLocation);

    OnClickListener oclDateDialog = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            FragmentTransaction ft = MainFragment.this.getActivity().getSupportFragmentManager()
                    .beginTransaction();
            Fragment prev = MainFragment.this.getActivity().getSupportFragmentManager()
                    .findFragmentByTag(OTPApp.TAG_FRAGMENT_DATE_TIME_DIALOG);
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);

            // Create and show the dialog.
            DateTimeDialog newFragment = new DateTimeDialog();

            Date dateDialogDate;
            if (mTripDate == null) {
                dateDialogDate = Calendar.getInstance().getTime();
            } else {
                dateDialogDate = mTripDate;
            }

            Bundle bundle = new Bundle();
            bundle.putSerializable(OTPApp.BUNDLE_KEY_TRIP_DATE, dateDialogDate);
            bundle.putBoolean(OTPApp.BUNDLE_KEY_ARRIVE_BY, mArriveBy);
            newFragment.setArguments(bundle);
            ft.commit();

            newFragment.show(MainFragment.this.getActivity().getSupportFragmentManager(),
                    OTPApp.TAG_FRAGMENT_DATE_TIME_DIALOG);
        }
    };
    mBtnDateDialog.setOnClickListener(oclDateDialog);

    AdapterView.OnItemSelectedListener itinerarySpinnerListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mFragmentListener.onItinerarySelected(position);

            if (!mAppResumed) {
                showRouteOnMap(mFragmentListener.getCurrentItinerary(), true);
            } else {
                showRouteOnMap(mFragmentListener.getCurrentItinerary(), false);
                mAppResumed = false;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    int currentItineraryIndex = mFragmentListener.getCurrentItineraryIndex();

    mItinerarySelectionSpinner.setSelection(currentItineraryIndex);
    mItinerarySelectionSpinner.setOnItemSelectedListener(itinerarySpinnerListener);

    mBikeTriangleParameters.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Double>() {
        @Override
        public void onRangeSeekBarValuesChanged(RangeSeekBar<?> rangeSeekBar, Double minValue,
                Double maxValue) {
            // handle changed range values
            Log.i(OTPApp.TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
        }

    });

    mDdlTravelMode.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TraverseModeSpinnerItem traverseModeSpinnerItem = (TraverseModeSpinnerItem) mDdlTravelMode
                    .getItemAtPosition(position);
            if (traverseModeSpinnerItem != null) {
                if (traverseModeSpinnerItem.getTraverseModeSet().contains(TraverseMode.BICYCLE)) {
                    setBikeOptimizationAdapter(true);
                    showBikeParameters(true);
                } else {
                    setBikeOptimizationAdapter(false);
                    showBikeParameters(false);
                }

                mBtnPlanTrip.setImageBitmap(BitmapFactory.decodeResource(getResources(),
                        DirectionsGenerator.getModeIcon(traverseModeSpinnerItem.getTraverseModeSet())));
            }
            Log.e(OTPApp.TAG, "Not possible to change travel mode because traverse mode is unknown"
                    + "for selected transport medium");
        }
    });

    mDdlOptimization.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            OptimizeSpinnerItem optimizeSpinnerItem = (OptimizeSpinnerItem) mDdlOptimization
                    .getItemAtPosition(position);
            if (optimizeSpinnerItem != null) {
                showBikeParameters(optimizeSpinnerItem.getOptimizeType().equals(OptimizeType.TRIANGLE));
            } else {
                Log.e(OTPApp.TAG, "Not possible to change optimization mode because selected"
                        + "optimization is unknown");
            }
        }
    });

    mBikeTriangleParameters.setOnRangeSeekBarChangeListener(this);
}

From source file:com.hughes.android.dictionary.DictionaryActivity.java

@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
    if (event.getUnicodeChar() != 0) {
        if (!searchView.hasFocus()) {
            setSearchText("" + (char) event.getUnicodeChar(), true);
            searchView.requestFocus();// www . j a  v  a 2s  . c  om
        }
        return true;
    }
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Log.d(LOG, "Clearing dictionary prefs.");
        // Pretend that we just autolaunched so that we won't do it again.
        // DictionaryManagerActivity.lastAutoLaunchMillis =
        // System.currentTimeMillis();
    }
    if (keyCode == KeyEvent.KEYCODE_ENTER) {
        Log.d(LOG, "Trying to hide soft keyboard.");
        final InputMethodManager inputManager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        View focus = getCurrentFocus();
        if (focus != null) {
            inputManager.hideSoftInputFromWindow(focus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:org.appcelerator.titanium.view.TiUIView.java

/**
 * Registers a callback to be invoked when a hardware key is pressed in this view.
 *
 * @param v The view to have the key listener to attach to.
 *//*from  w w  w  . j  ava  2s . c o  m*/
protected void registerForKeyPressEvents(final View v) {
    if (v == null) {
        return;
    }

    v.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                KrollDict data = new KrollDict();
                data.put(TiC.EVENT_PROPERTY_KEYCODE, keyCode);
                proxy.fireEvent(TiC.EVENT_KEY_PRESSED, data);

                switch (keyCode) {
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    if (proxy.hasListeners(TiC.EVENT_CLICK)) {
                        proxy.fireEvent(TiC.EVENT_CLICK, null);
                        return true;
                    }
                }
            }
            return false;
        }
    });
}

From source file:com.customdatepicker.time.TimePickerDialog.java

/**
 * For keyboard mode, processes key events.
 * @param keyCode the pressed key.// w w w . j  a  v a 2  s. c o  m
 * @return true if the key was successfully processed, false otherwise.
 */
private boolean processKeyUp(int keyCode) {
    if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
        if (isCancelable())
            dismiss();
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_TAB) {
        if (mInKbMode) {
            if (isTypedTimeFullyLegal()) {
                finishKbMode(true);
            }
            return true;
        }
    } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
        if (mInKbMode) {
            if (!isTypedTimeFullyLegal()) {
                return true;
            }
            finishKbMode(false);
        }
        if (mCallback != null) {
            mCallback.onTimeSet(this, mTimePicker.getHours(), mTimePicker.getMinutes(),
                    mTimePicker.getSeconds());
        }
        dismiss();
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_DEL) {
        if (mInKbMode) {
            if (!mTypedTimes.isEmpty()) {
                int deleted = deleteLastTypedKey();
                String deletedKeyStr;
                if (deleted == getAmOrPmKeyCode(AM)) {
                    deletedKeyStr = mAmText;
                } else if (deleted == getAmOrPmKeyCode(PM)) {
                    deletedKeyStr = mPmText;
                } else {
                    deletedKeyStr = String.format("%d", getValFromKeyCode(deleted));
                }
                Utils.tryAccessibilityAnnounce(mTimePicker, String.format(mDeletedKeyFormat, deletedKeyStr));
                updateDisplay(true);
            }
        }
    } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 || keyCode == KeyEvent.KEYCODE_2
            || keyCode == KeyEvent.KEYCODE_3 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
            || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 || keyCode == KeyEvent.KEYCODE_8
            || keyCode == KeyEvent.KEYCODE_9
            || (!mIs24HourMode && (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
        if (!mInKbMode) {
            if (mTimePicker == null) {
                // Something's wrong, because time picker should definitely not be null.
                Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
                return true;
            }
            mTypedTimes.clear();
            tryStartingKbMode(keyCode);
            return true;
        }
        // We're already in keyboard mode.
        if (addKeyIfLegal(keyCode)) {
            updateDisplay(false);
        }
        return true;
    }
    return false;
}

From source file:com.android.mail.ui.ConversationViewFragment.java

@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
    if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
        mOriginalKeyedView = view;/*from w w w .  ja  v a  2 s  . c o  m*/
    }

    if (mOriginalKeyedView != null) {
        final int id = mOriginalKeyedView.getId();
        final boolean isRtl = ViewUtils.isViewRtl(mOriginalKeyedView);
        final boolean isActionUp = keyEvent.getAction() == KeyEvent.ACTION_UP;
        final boolean isStart = KeyboardUtils.isKeycodeDirectionStart(keyCode, isRtl);
        final boolean isEnd = KeyboardUtils.isKeycodeDirectionEnd(keyCode, isRtl);
        final boolean isUp = keyCode == KeyEvent.KEYCODE_DPAD_UP;
        final boolean isDown = keyCode == KeyEvent.KEYCODE_DPAD_DOWN;

        // First we run the event by the controller
        // We manually check if the view+direction combination should shift focus away from the
        // conversation view to the thread list in two-pane landscape mode.
        final boolean isTwoPaneLand = mNavigationController.isTwoPaneLandscape();
        final boolean navigateAway = shouldNavigateAway(id, isStart, isTwoPaneLand);
        if (mNavigationController.onInterceptKeyFromCV(keyCode, keyEvent, navigateAway)) {
            return true;
        }

        // If controller didn't handle the event, check directional interception.
        if ((isStart || isEnd) && shouldInterceptLeftRightEvents(id, isStart, isEnd, isTwoPaneLand)) {
            return true;
        } else if (isUp || isDown) {
            // We don't do anything on up/down for overlay
            if (id == R.id.conversation_topmost_overlay) {
                return true;
            }

            // We manually handle up/down navigation through the overlay items because the
            // system's default isn't optimal for two-pane landscape since it's not a real list.
            final View next = mConversationContainer.getNextOverlayView(mOriginalKeyedView, isDown);
            if (next != null) {
                focusAndScrollToView(next);
            } else if (!isActionUp) {
                // Scroll in the direction of the arrow if next view isn't found.
                final int currentY = mWebView.getScrollY();
                if (isUp && currentY > 0) {
                    mWebView.scrollBy(0, -Math.min(currentY, DEFAULT_VERTICAL_SCROLL_DISTANCE_PX));
                } else if (isDown) {
                    final int webviewEnd = (int) (mWebView.getContentHeight() * mWebView.getScale());
                    final int currentEnd = currentY + mWebView.getHeight();
                    if (currentEnd < webviewEnd) {
                        mWebView.scrollBy(0,
                                Math.min(webviewEnd - currentEnd, DEFAULT_VERTICAL_SCROLL_DISTANCE_PX));
                    }
                }
            }
            return true;
        }

        // Finally we handle the special keys
        if (keyCode == KeyEvent.KEYCODE_BACK && id != R.id.conversation_topmost_overlay) {
            if (isActionUp) {
                mTopmostOverlay.requestFocus();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_ENTER && id == R.id.conversation_topmost_overlay) {
            if (isActionUp) {
                mWebView.scrollTo(0, 0);
                mConversationContainer.focusFirstMessageHeader();
            }
            return true;
        }
    }
    return false;
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * If there is a selected chip, delegate the key events to the selected chip.
 *///from  w w w .  j av  a  2s. co m
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
    if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
        /*if(mAlternatesPopup!=null&&mAlternatesPopup.isShowing())
          mAlternatesPopup.dismiss();*/
        removeChip(mSelectedChip, true);
    }
    switch (keyCode) {
    case KeyEvent.KEYCODE_ENTER:
    case KeyEvent.KEYCODE_DPAD_CENTER:
        if (event.hasNoModifiers()) {
            if (commitDefault())
                return true;
            if (mSelectedChip != null) {
                clearSelectedChip();
                return true;
            } else if (focusNext())
                return true;
        }
        break;
    }
    return super.onKeyDown(keyCode, event);
}