Example usage for android.view KeyEvent getAction

List of usage examples for android.view KeyEvent getAction

Introduction

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

Prototype

public final int getAction() 

Source Link

Document

Retrieve the action of this key event.

Usage

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

public boolean dispatchKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();

    LOG.debug("Got key event: " + keyCode + " with action " + action);

    if (searchMenuItem != null && searchMenuItem.isActionViewExpanded()) {
        boolean result = searchMenuItem.getActionView().dispatchKeyEvent(event);

        if (result) {
            return true;
        }//from w w  w.  j  a  v a 2 s. com
    }

    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP = 92;
    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM = 93;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP = 94;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM = 95;

    boolean nook_touch_up_press = false;

    if (isAnimating() && action == KeyEvent.ACTION_DOWN) {
        stopAnimating();
        return true;
    }

    /*
     * Tricky bit of code here: if we are NOT running TTS, we want to be
     * able to start it using the play/pause button.
     * 
     * When we ARE running TTS, we'll get every media event twice: once
     * through the receiver and once here if focused.
     * 
     * So, we only try to read media events here if tts is running.
     */
    if (!ttsIsRunning() && dispatchMediaKeyEvent(event)) {
        return true;
    }

    LOG.debug("Key event is NOT a media key event.");

    switch (keyCode) {

    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
        return handleVolumeButtonEvent(event);

    case KeyEvent.KEYCODE_DPAD_RIGHT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageDown(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_DPAD_LEFT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageUp(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_BACK:
        if (action == KeyEvent.ACTION_DOWN) {

            if (titleBarLayout.getVisibility() == View.VISIBLE) {
                hideTitleBar();
                updateFromPrefs();
                return true;
            } else if (bookView.hasPrevPosition()) {
                bookView.goBackInHistory();
                return true;
            }
        }

        return false;

    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP:
        nook_touch_up_press = true;
    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM:
        if (!Configuration.IS_NOOK_TOUCH || action == KeyEvent.ACTION_UP)
            return false;
        if (nook_touch_up_press == config.isNookUpButtonForward())
            pageDown(Orientation.HORIZONTAL);
        else
            pageUp(Orientation.HORIZONTAL);
        return true;
    }

    LOG.debug("Not handling key event: returning false.");
    return false;
}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

/**
 * Display a delete confirmation dialog to remove a device.<br>
 * The user is invited to enter his password to confirm the deletion.
 *
 * @param aDeviceInfoToDelete device info
 *//*  w  w  w.  j  a  va 2  s . com*/
private void displayDeviceDeletionDialog(final DeviceInfo aDeviceInfoToDelete) {
    if ((null != aDeviceInfoToDelete) && (null != aDeviceInfoToDelete.device_id)) {
        if (!TextUtils.isEmpty(mAccountPassword)) {
            deleteDevice(aDeviceInfoToDelete.device_id);
        } else {
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                    getActivity());
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View layout = inflater.inflate(R.layout.devices_settings_delete, null);

            final EditText passwordEditText = layout.findViewById(R.id.delete_password);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setTitle(R.string.devices_delete_dialog_title);
            builder.setView(layout);

            builder.setPositiveButton(R.string.devices_delete_submit_button_label,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (null != mSession) {
                                if (TextUtils.isEmpty(passwordEditText.toString())) {
                                    CommonActivityUtils.displayToast(VectorSettingsPreferencesFragment.this
                                            .getActivity().getApplicationContext(), "Password missing..");
                                    return;
                                }
                                mAccountPassword = passwordEditText.getText().toString();
                                deleteDevice(aDeviceInfoToDelete.device_id);
                            }
                        }
                    });

            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    hideLoadingView();
                }
            });

            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                        dialog.cancel();
                        hideLoadingView();
                        return true;
                    }
                    return false;
                }
            });

            builder.create().show();
        }
    } else {
        Log.e(LOG_TAG, "## displayDeviceDeletionDialog(): sanity check failure");
    }
}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

/**
 * Display a dialog containing the device ID, the device name and the "last seen" information.<>
 * This dialog allow to delete the corresponding device (see {@link #displayDeviceDeletionDialog(DeviceInfo)})
 *
 * @param aDeviceInfo the device information
 */// www .  j  a  v  a 2  s . c  o m
private void displayDeviceDetailsDialog(DeviceInfo aDeviceInfo) {
    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
            getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View layout = inflater.inflate(R.layout.devices_details_settings, null);

    if (null != aDeviceInfo) {
        //device ID
        TextView textView = layout.findViewById(R.id.device_id);
        textView.setText(aDeviceInfo.device_id);

        // device name
        textView = layout.findViewById(R.id.device_name);
        String displayName = (TextUtils.isEmpty(aDeviceInfo.display_name)) ? LABEL_UNAVAILABLE_DATA
                : aDeviceInfo.display_name;
        textView.setText(displayName);

        // last seen info
        textView = layout.findViewById(R.id.device_last_seen);
        if (!TextUtils.isEmpty(aDeviceInfo.last_seen_ip)) {
            String lastSeenIp = aDeviceInfo.last_seen_ip;
            String lastSeenTime = LABEL_UNAVAILABLE_DATA;

            if (null != getActivity()) {
                SimpleDateFormat dateFormatTime = new SimpleDateFormat(
                        getString(R.string.devices_details_time_format));
                String time = dateFormatTime.format(new Date(aDeviceInfo.last_seen_ts));

                DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
                lastSeenTime = dateFormat.format(new Date(aDeviceInfo.last_seen_ts)) + ", " + time;
            }
            String lastSeenInfo = this.getString(R.string.devices_details_last_seen_format, lastSeenIp,
                    lastSeenTime);
            textView.setText(lastSeenInfo);
        } else {
            // hide last time seen section
            layout.findViewById(R.id.device_last_seen_title).setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
        }

        // title & icon
        builder.setTitle(R.string.devices_details_dialog_title);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setView(layout);

        final DeviceInfo fDeviceInfo = aDeviceInfo;

        builder.setPositiveButton(R.string.rename, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                displayDeviceRenameDialog(fDeviceInfo);
            }
        });

        // disable the deletion for our own device
        if (!TextUtils.equals(mSession.getCrypto().getMyDevice().deviceId, fDeviceInfo.device_id)) {
            builder.setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    displayDeviceDeletionDialog(fDeviceInfo);
                }
            });
        }

        builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    dialog.cancel();
                    return true;
                }
                return false;
            }
        });

        builder.create().show();
    } else {
        Log.e(LOG_TAG, "## displayDeviceDetailsDialog(): sanity check failure");
        if (null != getActivity())
            CommonActivityUtils.displayToast(getActivity().getApplicationContext(),
                    "DeviceDetailsDialog cannot be displayed.\nBad input parameters.");
    }
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
    Logger.d(TAG, "onKeyUp keycode=%d", keyCode);
    switch (keyCode) {
    // Issue 248/*from w  w  w .ja v a2s. c o m*/
    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (!isInputViewShown()) {
            return super.onKeyUp(keyCode, event);
        }
        if (mAskPrefs.useVolumeKeyForLeftRight()) {
            // no need of vol up/down sound
            return true;
        }
    case KeyEvent.KEYCODE_DPAD_DOWN:
    case KeyEvent.KEYCODE_DPAD_UP:
    case KeyEvent.KEYCODE_DPAD_LEFT:
    case KeyEvent.KEYCODE_DPAD_RIGHT:
        if (getInputView() != null && getInputView().isShown() && getInputView().isShifted()) {
            event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(),
                    event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(),
                    KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
            InputConnection ic = getCurrentInputConnection();
            if (ic != null)
                ic.sendKeyEvent(event);

            return true;
        }
        break;
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        mMetaState = MyMetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyUp"));
        setInputConnectionMetaStateAsCurrentMetaKeyKeyListenerState();
        break;
    }
    return super.onKeyUp(keyCode, event);
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

void initialiseViews() {
    appBarLayout = (AppBarLayout) findViewById(R.id.lin);

    mScreenLayout = (CoordinatorLayout) findViewById(R.id.main_frame);
    buttonBarFrame = (FrameLayout) findViewById(R.id.buttonbarframe);

    //buttonBarFrame.setBackgroundColor(Color.parseColor(currentTab==1 ? skinTwo : skin));
    drawerHeaderLayout = getLayoutInflater().inflate(R.layout.drawerheader, null);
    drawerHeaderParent = (RelativeLayout) drawerHeaderLayout.findViewById(R.id.drawer_header_parent);
    drawerHeaderView = drawerHeaderLayout.findViewById(R.id.drawer_header);
    drawerHeaderView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override//w w w  .  j av a 2s  .c om
        public boolean onLongClick(View v) {
            Intent intent;
            if (SDK_INT < 19) {
                intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
            } else {
                intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

            }
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, image_selector_request_code);
            return false;
        }
    });
    drawerProfilePic = (RoundedImageView) drawerHeaderLayout.findViewById(R.id.profile_pic);
    mGoogleName = (TextView) drawerHeaderLayout.findViewById(R.id.account_header_drawer_name);
    mGoogleId = (TextView) drawerHeaderLayout.findViewById(R.id.account_header_drawer_email);
    toolbar = (Toolbar) findViewById(R.id.action_bar);
    /* For SearchView, see onCreateOptionsMenu(Menu menu)*/
    TOOLBAR_START_INSET = toolbar.getContentInsetStart();
    setSupportActionBar(toolbar);
    frameLayout = (FrameLayout) findViewById(R.id.content_frame);
    indicator_layout = findViewById(R.id.indicator_layout);
    mDrawerLinear = (ScrimInsetsRelativeLayout) findViewById(R.id.left_drawer);
    if (getAppTheme().equals(AppTheme.DARK))
        mDrawerLinear.setBackgroundColor(Utils.getColor(this, R.color.holo_dark_background));
    else
        mDrawerLinear.setBackgroundColor(Color.WHITE);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    //mDrawerLayout.setStatusBarBackgroundColor(Color.parseColor((currentTab==1 ? skinTwo : skin)));
    mDrawerList = (ListView) findViewById(R.id.menu_drawer);
    drawerHeaderView.setBackgroundResource(R.drawable.amaze_header);
    //drawerHeaderParent.setBackgroundColor(Color.parseColor((currentTab==1 ? skinTwo : skin)));
    if (findViewById(R.id.tab_frame) != null) {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, mDrawerLinear);
        mDrawerLayout.openDrawer(mDrawerLinear);
        mDrawerLayout.setScrimColor(Color.TRANSPARENT);
        isDrawerLocked = true;
    } else if (findViewById(R.id.tab_frame) == null) {

        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mDrawerLinear);
        mDrawerLayout.closeDrawer(mDrawerLinear);
        isDrawerLocked = false;
    }
    mDrawerList.addHeaderView(drawerHeaderLayout);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    fabBgView = findViewById(R.id.fab_bg);
    if (getAppTheme().equals(AppTheme.DARK)) {
        fabBgView.setBackgroundResource(R.drawable.fab_shadow_dark);
    }

    fabBgView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            floatingActionButton.close(true);
            if (isSearchViewEnabled)
                hideSearchView();
        }
    });

    pathbar = (LinearLayout) findViewById(R.id.pathbar);
    buttons = (LinearLayout) findViewById(R.id.buttons);
    scroll = (HorizontalScrollView) findViewById(R.id.scroll);
    scroll1 = (HorizontalScrollView) findViewById(R.id.scroll1);
    scroll.setSmoothScrollingEnabled(true);
    scroll1.setSmoothScrollingEnabled(true);
    ImageView divider = (ImageView) findViewById(R.id.divider1);
    if (getAppTheme().equals(AppTheme.LIGHT))
        divider.setImageResource(R.color.divider);
    else
        divider.setImageResource(R.color.divider_dark);

    setDrawerHeaderBackground();
    View settingsButton = findViewById(R.id.settingsbutton);
    if (getAppTheme().equals(AppTheme.DARK)) {
        settingsButton.setBackgroundResource(R.drawable.safr_ripple_black);
        ((ImageView) settingsButton.findViewById(R.id.settingicon))
                .setImageResource(R.drawable.ic_settings_white_48dp);
        ((TextView) settingsButton.findViewById(R.id.settingtext))
                .setTextColor(Utils.getColor(this, android.R.color.white));
    }
    settingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(MainActivity.this, PreferencesActivity.class);
            startActivity(in);
            finish();
        }

    });
    View appButton = findViewById(R.id.appbutton);
    if (getAppTheme().equals(AppTheme.DARK)) {
        appButton.setBackgroundResource(R.drawable.safr_ripple_black);
        ((ImageView) appButton.findViewById(R.id.appicon)).setImageResource(R.drawable.ic_doc_apk_white);
        ((TextView) appButton.findViewById(R.id.apptext))
                .setTextColor(Utils.getColor(this, android.R.color.white));
    }
    appButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            android.support.v4.app.FragmentTransaction transaction2 = getSupportFragmentManager()
                    .beginTransaction();
            transaction2.replace(R.id.content_frame, new AppsList());
            findViewById(R.id.lin).animate().translationY(0).setInterpolator(new DecelerateInterpolator(2))
                    .start();
            pending_fragmentTransaction = transaction2;
            if (!isDrawerLocked)
                mDrawerLayout.closeDrawer(mDrawerLinear);
            else
                onDrawerClosed();
            selectedStorage = SELECT_MINUS_2;
            adapter.toggleChecked(false);
        }
    });

    View ftpButton = findViewById(R.id.ftpbutton);
    if (getAppTheme().equals(AppTheme.DARK)) {
        ftpButton.setBackgroundResource(R.drawable.safr_ripple_black);
        ((ImageView) ftpButton.findViewById(R.id.ftpicon)).setImageResource(R.drawable.ic_ftp_dark);
        ((TextView) ftpButton.findViewById(R.id.ftptext))
                .setTextColor(Utils.getColor(this, android.R.color.white));
    }
    ftpButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            android.support.v4.app.FragmentTransaction transaction2 = getSupportFragmentManager()
                    .beginTransaction();
            transaction2.replace(R.id.content_frame, new FTPServerFragment());
            findViewById(R.id.lin).animate().translationY(0).setInterpolator(new DecelerateInterpolator(2))
                    .start();
            pending_fragmentTransaction = transaction2;
            if (!isDrawerLocked)
                mDrawerLayout.closeDrawer(mDrawerLinear);
            else
                onDrawerClosed();
            selectedStorage = SELECT_MINUS_2;
            adapter.toggleChecked(false);
        }
    });
    //getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor((currentTab==1 ? skinTwo : skin))));

    // status bar0
    if (SDK_INT == 20 || SDK_INT == 19) {
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        //tintManager.setStatusBarTintColor(Color.parseColor((currentTab==1 ? skinTwo : skin)));
        FrameLayout.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) findViewById(R.id.drawer_layout)
                .getLayoutParams();
        SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
        if (!isDrawerLocked)
            p.setMargins(0, config.getStatusBarHeight(), 0, 0);
    } else if (SDK_INT >= 21) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (isDrawerLocked) {
            window.setStatusBarColor((skinStatusBar));
        } else
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (colourednavigation)
            window.setNavigationBarColor(skinStatusBar);
    }

    searchViewLayout = (RelativeLayout) findViewById(R.id.search_view);
    searchViewEditText = (AppCompatEditText) findViewById(R.id.search_edit_text);
    ImageView clear = (ImageView) findViewById(R.id.search_close_btn);
    clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchViewEditText.setText("");
        }
    });
    findViewById(R.id.img_view_back).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideSearchView();
        }
    });
    searchViewEditText.setOnKeyListener(new TextView.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN)) {
                // Perform action on key press
                mainActivityHelper.search(searchViewEditText.getText().toString());
                hideSearchView();
                return true;
            }
            return false;
        }
    });

    //    searchViewEditText.setTextColor(Utils.getColor(this, android.R.color.black));
    //     searchViewEditText.setHintTextColor(Color.parseColor(BaseActivity.accentSkin));
}

From source file:com.android.tv.MainActivity.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (SystemProperties.LOG_KEYEVENT.getValue())
        Log.d(TAG, "dispatchKeyEvent(" + event + ")");
    // If an activity is closed on a back key down event, back key down events with none zero
    // repeat count or a back key up event can be happened without the first back key down
    // event which should be ignored in this activity.
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            mBackKeyPressed = true;//from  ww  w  .j a  v a  2 s.  co  m
        }
        if (!mBackKeyPressed) {
            return true;
        }
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mBackKeyPressed = false;
        }
    }

    // When side panel is closing, it has the focus.
    // Keep the focus, but just don't deliver the key events.
    if ((mOverlayRootView.hasFocusable() && !mOverlayManager.getSideFragmentManager().isHiding())
            || mOverlayManager.getSideFragmentManager().isActive()) {
        return super.dispatchKeyEvent(event);
    }
    if (BLACKLIST_KEYCODE_TO_TIS.contains(event.getKeyCode()) || KeyEvent.isGamepadButton(event.getKeyCode())) {
        // If the event is in blacklisted or gamepad key, do not pass it to session.
        // Gamepad keys are blacklisted to support TV UIs and here's the detail.
        // If there's a TIS granted RECEIVE_INPUT_EVENT, TIF sends key events to TIS
        // and return immediately saying that the event is handled.
        // In this case, fallback key will be injected but with FLAG_CANCELED
        // while gamepads support DPAD_CENTER and BACK by fallback.
        // Since we don't expect that TIS want to handle gamepad buttons now,
        // blacklist gamepad buttons and wait for next fallback keys.
        // TODO) Need to consider other fallback keys (e.g. ESCAPE)
        return super.dispatchKeyEvent(event);
    }
    return dispatchKeyEventToSession(event) || super.dispatchKeyEvent(event);
}

From source file:org.mdc.chess.MDChess.java

private void selectPgnSaveNewFileDialog() {
    setAutoMode(AutoMode.OFF);//w  w  w  .j a  v  a 2 s  .  c  o m
    View content = View.inflate(this, R.layout.create_pgn_file, null);

    final EditText fileNameView = (EditText) content.findViewById(R.id.create_pgn_filename);
    final TextInputLayout fileNameWrapper = (TextInputLayout) content
            .findViewById(R.id.create_pgn_filename_wrapper);
    fileNameWrapper.setHint(content.getResources().getString(R.string.filename));
    fileNameView.setText("");
    final Runnable savePGN = new Runnable() {
        public void run() {
            String pgnFile = fileNameView.getText().toString();
            if ((pgnFile.length() > 0) && !pgnFile.contains(".")) {
                pgnFile += ".pgn";
            }
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + pgnDir + sep + pgnFile;
            savePGNToFile(pathName);
        }
    };

    new MaterialDialog.Builder(this).title(R.string.select_pgn_file_save).customView(content, true)
            .positiveText(android.R.string.ok).negativeText(R.string.cancel)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    savePGN.run();
                }
            }).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                }
            }).show();

    fileNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                savePGN.run();
                return true;
            }
            return false;
        }
    });
}

From source file:org.bangbang.support.v4.widget.HListView.java

@Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // Dispatch in the normal way
        boolean handled = super.dispatchKeyEvent(event);
        if (!handled) {
            // If we didn't handle it...
            View focused = getFocusedChild();
            if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
                // ... and our focused child didn't handle it
                // ... give it to ourselves so we can scroll if necessary
                handled = onKeyDown(event.getKeyCode(), event);
            }//from  w ww  .java 2 s  . co m
        }
        return handled;
    }

From source file:org.mdc.chess.MDChess.java

private void newNetworkEngineDialog() {
    View content = View.inflate(this, R.layout.create_network_engine, null);
    final EditText engineNameView = (EditText) content.findViewById(R.id.create_network_engine);
    final TextInputLayout engineNameWrapper = (TextInputLayout) content
            .findViewById(R.id.create_network_engine_wrapper);
    engineNameWrapper.setHint(content.getResources().getString(R.string.engine_name));
    engineNameView.setText("");
    final Runnable createEngine = new Runnable() {
        public void run() {
            String engineName = engineNameView.getText().toString();
            String sep = File.separator;
            String pathName = Environment.getExternalStorageDirectory() + sep + engineDir + sep + engineName;
            File file = new File(pathName);
            boolean nameOk = true;
            int errMsg = -1;
            if (engineName.contains("/")) {
                nameOk = false;/*from w ww.  j a  v a  2 s .  c  o  m*/
                errMsg = R.string.slash_not_allowed;
            } else if (reservedEngineName(engineName) || file.exists()) {
                nameOk = false;
                errMsg = R.string.engine_name_in_use;
            }
            if (!nameOk) {
                Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
                networkEngineDialog();
                return;
            }
            networkEngineToConfig = pathName;
            networkEngineConfigDialog();
        }
    };
    new MaterialDialog.Builder(this).title(R.string.create_network_engine).customView(content, true)
            .positiveText(android.R.string.ok).negativeText(R.string.cancel)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    createEngine.run();
                }
            }).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    networkEngineDialog();
                }
            }).show();

    engineNameView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                createEngine.run();
                return true;
            }
            return false;
        }
    });
}

From source file:org.mdc.chess.MDChess.java

private void networkEngineConfigDialog() {
    View content = View.inflate(this, R.layout.network_engine_config, null);
    final EditText hostNameView = (EditText) content.findViewById(R.id.network_engine_host);
    final EditText portView = (EditText) content.findViewById(R.id.network_engine_port);
    String hostName = "";
    String port = "0";
    try {//  w  ww  . ja v  a  2s  .  com
        if (EngineUtil.isNetEngine(networkEngineToConfig)) {
            String[] lines = Util.readFile(networkEngineToConfig);
            if (lines.length > 1) {
                hostName = lines[1];
            }
            if (lines.length > 2) {
                port = lines[2];
            }
        }
    } catch (IOException e1) {
        Log.d("Exception", e1.toString());
    }
    hostNameView.setText(hostName);
    portView.setText(port);
    final Runnable writeConfig = new Runnable() {
        public void run() {
            String hostName = hostNameView.getText().toString();
            String port = portView.getText().toString();
            try {
                FileWriter fw = new FileWriter(new File(networkEngineToConfig), false);
                fw.write("NETE\n");
                fw.write(hostName);
                fw.write("\n");
                fw.write(port);
                fw.write("\n");
                fw.close();
                setEngineOptions(true);
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    };
    new MaterialDialog.Builder(this).title(R.string.configure_network_engine).customView(content, true)
            .positiveText(android.R.string.ok).negativeText(R.string.cancel).neutralText(R.string.delete)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    writeConfig.run();
                    networkEngineDialog();
                }
            }).onNeutral(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    deleteNetworkEngineDialog();
                }
            }).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    networkEngineDialog();
                }
            });

    portView.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                writeConfig.run();
                networkEngineDialog();
                return true;
            }
            return false;
        }
    });
}