Example usage for android.view KeyEvent ACTION_DOWN

List of usage examples for android.view KeyEvent ACTION_DOWN

Introduction

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

Prototype

int ACTION_DOWN

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

Click Source Link

Document

#getAction value: the key has been pressed down.

Usage

From source file:org.kiwix.kiwixmobile.KiwixMobileActivity.java

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (getCurrentWebView().canGoBack()) {
                getCurrentWebView().goBack();
            } else {
                finish();//from w  w  w.  ja v a  2 s .  c om
            }
            if (compatCallback.mIsActive) {
                compatCallback.finish();
            }
            return true;
        case KeyEvent.KEYCODE_MENU:
            openOptionsMenu();
            return true;
        }
    }
    return false;
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    Log.w(TAG, "onKeyDown");
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

        Log.w(TAG, "onKeyDown, KEYCODE_BACK");
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            //??  
            if (MyFloatView.mPlayViewPrepareStatus) {
                Log.e("smallstar", "MyFloatView.mPlayViewPrepareStatus is true!");
                MyFloatView.mPlayViewStatus = false;
                MyFloatView.onExit();/*from  w  w w.  j  av a  2  s.  c o  m*/
            }

            if (mWebView.getOriginalUrl().equals("http://localhost:8080/console/settings/basicsettings.html")) {
                stopService(new Intent(this, DaemonService.class));
                stopService(new Intent(this, IJettyService.class));
                finish();
            } else {
                //mWebView.loadUrl("http://localhost:8080/console/settings/index.html");
                mWebView.loadUrl("http://localhost:8080/console/settings/basicsettings.html");
            }
        }
        return true;
    }
    return super.dispatchKeyEvent(event);
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:

            String d = usernum + "-" + getStripNumber(prefs.getString(stored_chatuserNumber, "")) + "-nt";
            if (ChatSocket.socket != null) {
                ChatSocket.ps.print(d);/*www  .ja v a  2 s .c o m*/
            }

            Log.d("ps d onKeyDown", d + " @");

            MessageFragment.keyboard_flag = false;
            btn_emoticon_show.setImageResource(R.drawable.smily_icon);
            if (Fl_Emoticon_Holder.getVisibility() == 0) {
                Fl_Emoticon_Holder.setVisibility(FrameLayout.GONE);
            } else {
                finish();
            }
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

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

/**
 * Hook up buttons, lists, and edittext with functionality.
 *//*from   w w  w .ja  v a  2 s. c om*/
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 key down / key up pair to the current editor.
 *///from  ww  w. java 2  s. co  m
private void keyDownUp(int keyEventCode) {
    ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
    ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));
}

From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java

public static void linkButtons(Context context, RemoteViews views, boolean playerActive) {

    Intent intent = new Intent(context, playerActive ? DownloadActivity.class : MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.appwidget_coverart, pendingIntent);
    views.setOnClickPendingIntent(R.id.appwidget_top, pendingIntent);

    // Emulate media button clicks.
    intent = new Intent("1");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_play, pendingIntent);

    intent = new Intent("2");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_next, pendingIntent);

    intent = new Intent("3");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_previous, pendingIntent);

    intent = new Intent("4");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_stop, pendingIntent);
}

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

private void addInterfaceListeners() {

    final OnMapClickListener onMapClickListener = new OnMapClickListener() {
        @Override/*ww w.  j  av  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.iiordanov.bVNC.RemoteCanvasActivity.java

@Override
public boolean onKey(View v, int keyCode, KeyEvent evt) {

    boolean consumed = false;

    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (evt.getAction() == KeyEvent.ACTION_DOWN)
            return super.onKeyDown(keyCode, evt);
        else/*from  w  ww .  j  a  v  a  2 s.c o  m*/
            return super.onKeyUp(keyCode, evt);
    }

    try {
        if (evt.getAction() == KeyEvent.ACTION_DOWN || evt.getAction() == KeyEvent.ACTION_MULTIPLE) {
            consumed = inputHandler.onKeyDown(keyCode, evt);
        } else if (evt.getAction() == KeyEvent.ACTION_UP) {
            consumed = inputHandler.onKeyUp(keyCode, evt);
        }
        resetOnScreenKeys(keyCode);
    } catch (NullPointerException e) {
    }

    return consumed;
}

From source file:com.tct.mail.ui.ConversationListFragment.java

@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
    SwipeableListView list = (SwipeableListView) view;
    // Don't need to handle ENTER because it's auto-handled as a "click".
    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
        if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
            if (mKeyInitiatedFromList) {
                onListItemSelected(list.getSelectedView(), list.getSelectedItemPosition());
            }/*from  w ww. j ava 2 s .  c  o m*/
            mKeyInitiatedFromList = false;
        } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
            mKeyInitiatedFromList = true;
        }
        return true;
    } else if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            final int position = list.getSelectedItemPosition();
            final Object item = getAnimatedAdapter().getItem(position);
            if (item != null && item instanceof ConversationCursor) {
                final Conversation conv = ((ConversationCursor) item).getConversation();
                mCallbacks.onConversationFocused(conv);
            }
        }
    }
    return false;
}

From source file:com.fishstix.dosboxfree.DBGLSurfaceView.java

private final int getMappedKeyCode(final int button, final KeyEvent event) {
    switch (button) {
    case MAP_LEFTCLICK:
        DosBoxControl.nativeMouse(0, 0, 0, 0, (event.getAction() == KeyEvent.ACTION_DOWN) ? 0 : 1, BTN_A);
        return MAP_EVENT_CONSUMED;
    case MAP_RIGHTCLICK:
        DosBoxControl.nativeMouse(0, 0, 0, 0, (event.getAction() == KeyEvent.ACTION_DOWN) ? 0 : 1, BTN_B);
        return MAP_EVENT_CONSUMED;
    case MAP_JOYBTN_A:
        DosBoxControl.nativeJoystick(0, 0, (event.getAction() == KeyEvent.ACTION_DOWN) ? 0 : 1, BTN_A);
        return MAP_EVENT_CONSUMED;
    case MAP_JOYBTN_B:
        DosBoxControl.nativeJoystick(0, 0, (event.getAction() == KeyEvent.ACTION_DOWN) ? 0 : 1, BTN_B);
        return MAP_EVENT_CONSUMED;
    case MAP_CYCLEUP:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (mParent.mTurboOn) {
                mParent.mTurboOn = false;
                DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_TURBO_ON, mParent.mTurboOn ? 1 : 0, null,
                        true);/*w w w.  j  a v a  2  s  . c o m*/
            }
            DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_CYCLE_ADJUST, 1, null, true);
            if (DosBoxControl.nativeGetAutoAdjust()) {
                Toast.makeText(mParent, "Auto Cycles [" + DosBoxControl.nativeGetCycleCount() + "%]",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mParent, "DosBox Cycles: " + DosBoxControl.nativeGetCycleCount(),
                        Toast.LENGTH_SHORT).show();
            }
        }
        return MAP_EVENT_CONSUMED;
    case MAP_CYCLEDOWN:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (mParent.mTurboOn) {
                mParent.mTurboOn = false;
                DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_TURBO_ON, mParent.mTurboOn ? 1 : 0, null,
                        true);
            }
            DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_CYCLE_ADJUST, 0, null, true);
            if (DosBoxControl.nativeGetAutoAdjust()) {
                Toast.makeText(mParent, "Auto Cycles [" + DosBoxControl.nativeGetCycleCount() + "%]",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mParent, "DosBox Cycles: " + DosBoxControl.nativeGetCycleCount(),
                        Toast.LENGTH_SHORT).show();
            }
        }
        return MAP_EVENT_CONSUMED;
    case MAP_SHOWKEYBOARD:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            DBMenuSystem.doShowKeyboard(mParent);
        }
        return MAP_EVENT_CONSUMED;
    case MAP_SPECIALKEYS:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mContextMenu = DBMenuSystem.CONTEXT_MENU_SPECIAL_KEYS;
            mParent.openContextMenu(this);
        }
        return MAP_EVENT_CONSUMED;
    case MAP_ADJUSTCYCLES:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mContextMenu = DBMenuSystem.CONTEXT_MENU_CYCLES;
            mParent.openContextMenu(this);
        }
        return MAP_EVENT_CONSUMED;
    case MAP_ADJUSTFRAMES:
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mContextMenu = DBMenuSystem.CONTEXT_MENU_FRAMESKIP;
            mParent.openContextMenu(this);
        }
        return MAP_EVENT_CONSUMED;
    case MAP_UNLOCK_SPEED:
        if (mParent.mTurboOn) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_TURBO_ON, 0, null, true); // turn off
                mParent.mTurboOn = false;
            }
        } else {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                DBMain.nativeSetOption(DBMenuSystem.DOSBOX_OPTION_ID_TURBO_ON, 1, null, true); // turn on
                mParent.mTurboOn = true;
            }
        }
        return MAP_EVENT_CONSUMED;
    default:
        return button;
    }
}