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.code.android.vibevault.SearchScreen.java

private void init() {

    // Set up the date selection spinner.
    spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.date_modifier,
            android.R.layout.simple_spinner_item);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    dateModifierSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override//from  w w w . ja va 2  s  .  c o  m
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            VibeVault.dateSearchModifierPos = pos;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    dateModifierSpinner.setAdapter(spinnerAdapter);
    dateModifierSpinner.setSelection(VibeVault.dateSearchModifierPos);

    searchDrawer.setOnDrawerScrollListener(new OnDrawerScrollListener() {

        @Override
        public void onScrollEnded() {
        }

        @Override
        public void onScrollStarted() {
            vibrator.vibrate(50);
        }

    });
    artistSearchInput.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (isMoreSearch(s.toString(), yearSearchInput.getText().toString())) {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.morebutton), null, null, null);
                searchButton.setText("More");
            } else {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.searchbutton_plain), null, null, null);
                searchButton.setText("Search");
            }
        }

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

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

    });
    yearSearchInput.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (isMoreSearch(artistSearchInput.getText().toString(), s.toString())) {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.morebutton), null, null, null);
                searchButton.setText("More");
            } else {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.searchbutton_plain), null, null, null);
                searchButton.setText("Search");
            }
        }

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

        }

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

    });
    searchDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
        @Override
        public void onDrawerOpened() {
            searchList.setBackgroundDrawable(getResources().getDrawable(R.drawable.backgrounddrawableblue));
            searchList.getBackground().setDither(true);
            searchList.setEnabled(false);
            handleText.setText("Search Panel");
            handleText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
            artistSearchInput.setText(VibeVault.artistSearchText);

            if (VibeVault.yearSearchInt != -1) {
                yearSearchInput.setText(String.valueOf(VibeVault.yearSearchInt));
            } else {
                yearSearchInput.setText("");
            }
            dateModifierSpinner.setSelection(VibeVault.dateSearchModifierPos);
        }
    });
    searchDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
        @Override
        public void onDrawerClosed() {
            searchList.setBackgroundColor(Color.BLACK);
            searchList.setEnabled(true);
            handleText.setText("Drag up to search...");
            handleText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 28);
        }
    });

    // Set listeners in the show details and artist search bars for the enter key.
    OnKeyListener enterListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (!(artistSearchInput.getText().toString().equals(""))) {
                    VibeVault.artistSearchText = artistSearchInput.getText().toString();
                    if (setDate()) {
                        executeSearch(makeSearchURLString(1));
                        pageNum = 1;
                        searchDrawer.close();
                        return true;
                    }
                }
            }
            return false;
        }
    };
    this.artistSearchInput.setOnKeyListener(enterListener);

    this.searchButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            String query = artistSearchInput.getText().toString();
            // Blank
            if (query.equals("")) {
                vibrator.vibrate(50);
                Toast.makeText(getBaseContext(), "You need a query first...", Toast.LENGTH_SHORT).show();
                return;
            }
            // Search more
            else if (isMoreSearch(artistSearchInput.getText().toString(),
                    yearSearchInput.getText().toString())) {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.morebutton), null, null, null);
                searchButton.setText("More");
                dateModifierSpinner.setSelection(VibeVault.dateSearchModifierPos);
                // pageNum is incremented then searched with to get the next
                // page.
                executeSearch(makeSearchURLString(++pageNum));
                vibrator.vibrate(50);
                searchDrawer.close();
            }
            // New search
            else {
                searchButton.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.searchbutton_plain), null, null, null);
                searchButton.setText("Search");
                VibeVault.searchResults.clear();
                VibeVault.artistSearchText = artistSearchInput.getText().toString();
                if (setDate()) {
                    // "1" is passed to retrieve page number 1.
                    vibrator.vibrate(50);
                    executeSearch(makeSearchURLString(1));
                    pageNum = 1;
                    searchDrawer.close();
                }
            }

        }
    });

    this.settingsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            launchSettingsDialog();
            vibrator.vibrate(50);
        }
    });

    this.clearButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            artistSearchInput.setText("");
            yearSearchInput.setText("");
            VibeVault.artistSearchText = "";
            VibeVault.yearSearchInt = -1;
            searchButton.setCompoundDrawablesWithIntrinsicBounds(
                    getResources().getDrawable(R.drawable.searchbutton_plain), null, null, null);
            searchButton.setText("Search");
            VibeVault.searchResults.clear();
            refreshSearchList();
            vibrator.vibrate(50);
        }
    });

    searchList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            ArchiveShowObj show = (ArchiveShowObj) searchList.getItemAtPosition(position);
            Intent i = new Intent(SearchScreen.this, ShowDetailsScreen.class);
            i.putExtra("Show", show);
            startActivity(i);
        }
    });

    // Create the directory for our app if it don't exist.
    appRootDir = new File(Environment.getExternalStorageDirectory(), VibeVault.APP_DIRECTORY);
    if (!appRootDir.isFile() || !appRootDir.isDirectory()) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            appRootDir.mkdirs();
        } else {
            Toast.makeText(getBaseContext(), "sdcard is unwritable...  is it mounted on the computer?",
                    Toast.LENGTH_SHORT).show();
        }
    }
    artistSearchInput.setText(VibeVault.artistSearchText);
    if (VibeVault.yearSearchInt != -1) {
        yearSearchInput.setText(String.valueOf(VibeVault.yearSearchInt));
    } else {
        yearSearchInput.setText("");
    }
    dateModifierSpinner.setSelection(VibeVault.dateSearchModifierPos);

}

From source file:com.arlib.floatingsearchview.FloatingSearchView.java

private void setupQueryBar() {

    if (!isInEditMode() && mHostActivity != null)
        mHostActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    mOverflowMenu.setOnClickListener(new OnClickListener() {
        @Override/*ww w . ja v a  2  s .co  m*/
        public void onClick(View v) {

            mMenuPopupHelper.show();
        }
    });

    mMenuBuilder.setCallback(new MenuBuilder.Callback() {
        @Override
        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {

            if (mOnOverflowMenuItemListener != null)
                mOnOverflowMenuItemListener.onMenuItemSelected(item);

            //todo check if we should care about this return or not
            return false;
        }

        @Override
        public void onMenuModeChange(MenuBuilder menu) {
        }

    });

    mVoiceInputOrClearButton.setVisibility(mShowVoiceInput ? View.VISIBLE : View.INVISIBLE);
    mVoiceInputOrClearButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mSearchInput.getText().length() == 0) {

                startVoiceInput();
            } else {

                mSearchInput.setText("");
            }
        }
    });

    mSearchBarTitle.setVisibility(GONE);
    mSearchBarTitle.setTextColor(getResources().getColor(R.color.gray_active_icon));

    mSearchInput.addTextChangedListener(new TextWatcherAdapter() {

        public void onTextChanged(final CharSequence s, int start, int before, int count) {

            if (mSkipTextChangeEvent) {
                mSkipTextChangeEvent = false;
            } else {

                if (mSearchInput.getText().length() == 0) {

                    if (mShowVoiceInput)
                        changeIcon(mVoiceInputOrClearButton, mIconMic, true);
                    else
                        mVoiceInputOrClearButton.setVisibility(View.INVISIBLE);

                } else if (mOldQuery.length() == 0) {
                    changeIcon(mVoiceInputOrClearButton, mIconClear, true);
                    mVoiceInputOrClearButton.setVisibility(View.VISIBLE);
                }

                if (mQueryListener != null && mIsFocused)
                    mQueryListener.onSearchTextChanged(mOldQuery, mSearchInput.getText().toString());

                mOldQuery = mSearchInput.getText().toString();
            }

        }

    });

    mSearchInput.setOnFocusChangeListener(new TextView.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            if (mSkipQueryFocusChangeEvent) {
                mSkipQueryFocusChangeEvent = false;
            } else {

                if (hasFocus != mIsFocused)
                    setSearchFocused(hasFocus);
            }
        }
    });

    mSearchInput.setOnKeyListener(new OnKeyListener() {

        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {

            if (mShowSearchKey && keyCode == KeyEvent.KEYCODE_ENTER) {

                setSearchFocused(false);

                if (mSearchListener != null)
                    mSearchListener.onSearchAction();

                return true;
            }
            return false;
        }
    });

    refreshLeftIcon();

    mMenuSearchOrExitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mSearchInput.isFocused()) {

                setSearchFocused(false);
            } else {

                if (mShowMenuAction) {

                    toggleMenu();
                } else {

                    setSearchFocused(true);
                }
            }

        }
    });
}

From source file:com.googlecode.eyesfree.brailleback.IMENavigationModeTest.java

/**
 * Tests the behaviour of the "text and navigation" mode.
 */// w w w . ja  v  a 2s  .  c  o  m
public void testTextAndNavigationMode() {
    EditorInfo ei = new EditorInfo();

    // Mock out the AccessibilityNodeInfo.
    // The class actually uses the compat variant, but on recent API
    // releases (including the test environment) they should call through.
    AccessibilityNodeInfo rawNode = mock(AccessibilityNodeInfo.class);
    when(mAccessibilityService.getRootInActiveWindow()).thenReturn(rawNode);
    when(rawNode.findFocus(AccessibilityNodeInfo.FOCUS_INPUT)).thenReturn(rawNode);
    when(rawNode.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY)).thenReturn(rawNode);
    when(rawNode.getClassName()).thenReturn("com.example.ExampleWebView");
    when(mSelfBrailleManager.hasContentForNode(compatWrapperForNode(rawNode))).thenReturn(true);

    mIMENavMode.onActivate();
    mIMENavMode.onCreateIME();
    verify(mNext).onActivate();
    mIMENavMode.onBindInput();
    mIMENavMode.onStartInput(ei, false /* restarting */);
    verify(mSelfBrailleManager, atLeastOnce()).setImeOpen(false);
    verify(mSelfBrailleManager, never()).setImeOpen(true);
    mIMENavMode.onStartInputView(ei, false /* restarting */);

    assertEquals(mBrailleTranslator, mIMENavMode.getBrailleTranslator());
    assertNull(mIMENavMode.getDisplayManager());
    assertEquals(mFeedbackManager, mIMENavMode.getFeedbackManager());
    verify(mSelfBrailleManager, atLeastOnce()).setImeOpen(true);

    AccessibilityEvent accessibilityEvent = AccessibilityEvent.obtain();
    try {
        mIMENavMode.onObserveAccessibilityEvent(accessibilityEvent);
        verify(mNext).onObserveAccessibilityEvent(accessibilityEvent);
    } finally {
        accessibilityEvent.recycle();
    }

    accessibilityEvent = AccessibilityEvent.obtain();
    try {
        mIMENavMode.onAccessibilityEvent(accessibilityEvent);
        verify(mNext).onAccessibilityEvent(accessibilityEvent);
    } finally {
        accessibilityEvent.recycle();
    }

    AccessibilityNodeInfoCompat node = AccessibilityNodeInfoCompat.obtain();
    try {
        mIMENavMode.onInvalidateAccessibilityNode(node);
        verify(mNext).onInvalidateAccessibilityNode(node);
    } finally {
        node.recycle();
    }

    DisplayManager.Content content = new DisplayManager.Content("");
    mIMENavMode.onPanLeftOverflow(content);
    verify(mNext).onPanLeftOverflow(content);
    mIMENavMode.onPanRightOverflow(content);
    verify(mNext).onPanRightOverflow(content);

    BrailleInputEvent inputEvent = new BrailleInputEvent(BrailleInputEvent.CMD_KEY_ENTER, 0, 0);
    mIMENavMode.onMappedInputEvent(inputEvent, content);
    verify(mNext, never()).onMappedInputEvent(inputEvent, content);
    verify(mIME).sendAndroidKey(KeyEvent.KEYCODE_ENTER);

    inputEvent = new BrailleInputEvent(BrailleInputEvent.CMD_KEY_DEL, 0, 0);
    mIMENavMode.onMappedInputEvent(inputEvent, content);
    verify(mNext, never()).onMappedInputEvent(inputEvent, content);
    verify(mIME).sendAndroidKey(KeyEvent.KEYCODE_DEL);

    inputEvent = new BrailleInputEvent(BrailleInputEvent.CMD_BRAILLE_KEY, 0x1b, 0);
    mIMENavMode.onMappedInputEvent(inputEvent, content);
    verify(mNext, never()).onMappedInputEvent(inputEvent, content);
    verify(mIME).handleBrailleKey(0x1b);

    inputEvent = new BrailleInputEvent(BrailleInputEvent.CMD_ACTIVATE_CURRENT, 0, 0);
    mIMENavMode.onMappedInputEvent(inputEvent, content);
    verify(mNext).onMappedInputEvent(inputEvent, content);
    verify(mIME, never()).sendDefaultAction();

    inputEvent = new BrailleInputEvent(BrailleInputEvent.CMD_ROUTE, 0, 0);
    mIMENavMode.onMappedInputEvent(inputEvent, content);
    verify(mNext).onMappedInputEvent(inputEvent, content);
    verify(mIME, never()).route(anyInt(), any(DisplayManager.Content.class));

    // Nothing above this point should have triggered an action on the
    // accessibility node.
    verify(rawNode, never()).performAction(anyInt(), any(Bundle.class));
    verifyEventCausesNavigation(BrailleInputEvent.CMD_NAV_ITEM_NEXT, ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
            MOVEMENT_GRANULARITY_CHARACTER, rawNode, content);
    verifyEventCausesNavigation(BrailleInputEvent.CMD_NAV_ITEM_PREVIOUS,
            ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, MOVEMENT_GRANULARITY_CHARACTER, rawNode, content);
    verifyEventCausesNavigation(BrailleInputEvent.CMD_NAV_LINE_NEXT, ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
            MOVEMENT_GRANULARITY_LINE, rawNode, content);
    verifyEventCausesNavigation(BrailleInputEvent.CMD_NAV_LINE_PREVIOUS,
            ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, MOVEMENT_GRANULARITY_LINE, rawNode, content);

    Mockito.reset(mSelfBrailleManager);

    mIMENavMode.onFinishInputView(true);
    verify(mSelfBrailleManager).setImeOpen(false);
    mIMENavMode.onFinishInput();
    mIMENavMode.onUnbindInput();
    mIMENavMode.onDestroyIME();
    verify(mSelfBrailleManager, never()).setImeOpen(true);

    // Deactivate, but make sure it didn't happen too early.
    verify(mNext, never()).onDeactivate();
    mIMENavMode.onDeactivate();
    verify(mNext).onDeactivate();
}

From source file:com.philliphsu.bottomsheetpickers.time.grid.GridTimePickerDialog.java

/**
 * For keyboard mode, processes key events.
 * @param keyCode the pressed key.//from  w  w  w. jav  a2 s.com
 * @return true if the key was successfully processed, false otherwise.
 */
private boolean processKeyUp(int keyCode) {
    if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
        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);
        }
        onTimeSet(mTimePicker, mTimePicker.getHours(), mTimePicker.getMinutes());
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_DEL) {
        if (mInKbMode) {
            if (!mTypedTimes.isEmpty()) {
                int deleted = deleteLastTypedKey();
                String deletedKeyStr;
                if (deleted == getAmOrPmKeyCode(HALF_DAY_1)) {
                    deletedKeyStr = mAmText;
                } else if (deleted == getAmOrPmKeyCode(HALF_DAY_2)) {
                    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(HALF_DAY_1) || keyCode == getAmOrPmKeyCode(HALF_DAY_2)))) {
        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.mattfred.betterpickers.radialtimepicker.RadialTimePickerDialogFragment.java

/**
 * For keyboard mode, processes key events.
 *
 * @param keyCode the pressed key./*w w  w.  j  ava  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) {
        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(RadialTimePickerDialogFragment.this, mTimePicker.getHours(),
                    mTimePicker.getMinutes());
        }
        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.lofland.housebot.BotController.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.housebot);/*from   ww w.ja v a 2 s .c  om*/
    Log.d(TAG, "onCreate");

    /*
     * TODO: If you need to maintain and pass around context:
     * http://stackoverflow.com/questions/987072/using-application-context-everywhere
     */

    // Display start up toast:
    // http://developer.android.com/guide/topics/ui/notifiers/toasts.html
    Context context = getApplicationContext();
    CharSequence text = "ex Nehilo!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    // Display said toast
    toast.show();

    /*
     *  Turn on WiFi if it is off
     *  http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
     */
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    // Prevent keyboard from popping up as soon as app launches: (it works!)
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    /*
     * Keep the screen on, because as long as we are talking to the robot, this needs to be up http://stackoverflow.com/questions/9335908/how-to- prevent-the-screen-of
     * -an-android-device-to-turn-off-during-the-execution
     */
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    /*
     * One or more of these three lines sets the screen to minimum brightness, Which should extend battery drain, and be less distracting on the robot.
     */
    final WindowManager.LayoutParams winParams = this.getWindow().getAttributes();
    winParams.screenBrightness = 0.01f;
    winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;

    // The "Connect" screen has a "Name" and "Address box"
    // I'm not really sure what one puts in these, and if you leave them
    // empty it works fine.
    // So not 110% sure what to do with these. Can the text just be: ""?
    // Just comment these out, and run the command with nulls?
    // mName = (EditText) findViewById(R.id.name_edit);
    // mAddress = (EditText) findViewById(R.id.address_edit);
    // The NXT Remote Control app pops up a list of seen NXTs, so maybe I
    // need to implement that instead.

    // Text to speech
    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtSpeakText);

    // Now we need a Robot object before we an use any Roboty values!
    // We can pass defaults in or use the ones it provides
    myRobot = new Robot(INITIALTRAVELSPEED, INITIALROTATESPEED, DEFAULTVIEWANGLE);
    // We may have to pass this robot around a bit. ;)

    // Status Lines
    TextView distanceText = (TextView) findViewById(R.id.distanceText);
    distanceText.setText("???");
    TextView distanceLeftText = (TextView) findViewById(R.id.distanceLeftText);
    distanceLeftText.setText("???");
    TextView distanceRightText = (TextView) findViewById(R.id.distanceRightText);
    distanceRightText.setText("???");
    TextView headingText = (TextView) findViewById(R.id.headingText);
    headingText.setText("???");
    TextView actionText = (TextView) findViewById(R.id.isDoingText);
    actionText.setText("None");

    // Travel speed slider bar
    SeekBar travelSpeedBar = (SeekBar) findViewById(R.id.travelSpeed_seekBar);
    travelSpeedBar.setProgress(myRobot.getTravelSpeed());
    travelSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setTravelSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    // View angle slider bar
    SeekBar viewAngleBar = (SeekBar) findViewById(R.id.viewAngle_seekBar);
    viewAngleBar.setProgress(myRobot.getViewAngle());
    viewAngleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setViewAngle(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d(TAG, "View Angle Slider ");
            /*
             * If this gets sent every few milliseconds with the normal output, then there is no need to send a specific command every time it changes!
             */
            // sendCommandToRobot(Command.VIEWANGLE);
        }
    });

    // Rotation speed slider bar speedSP_seekBar
    SeekBar rotateSpeedBar = (SeekBar) findViewById(R.id.rotateSpeed_seekBar);
    rotateSpeedBar.setProgress(myRobot.getRotateSpeed());
    rotateSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setRotateSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    /*
     * This is where we find the four direction buttons defined So we could define ALL buttons this way, set up an ENUM with all options, and call the same function for ALL
     * options!
     * 
     * Just be sure the "release" only stops the robot on these, and not every button on the screen.
     * 
     * Maybe see how the code I stole this form does it?
     */
    Button buttonUp = (Button) findViewById(R.id.forward_button);
    buttonUp.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.FORWARD));
    Button buttonDown = (Button) findViewById(R.id.reverse_button);
    buttonDown.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.REVERSE));
    Button buttonLeft = (Button) findViewById(R.id.left_button);
    buttonLeft.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.LEFT));
    Button buttonRight = (Button) findViewById(R.id.right_button);
    buttonRight.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.RIGHT));

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });

    /*
     * This causes the typed text to be spoken when the Enter key is pressed.
     */
    txtText.setOnKeyListener(new View.OnKeyListener() {
        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) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                speakOut();
                return true;
            }
            return false;
        }
    });

    // Connect button
    connectToggleButton = (ToggleButton) findViewById(R.id.connectToggleButton);
    connectToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                Log.d(TAG, "Connect button Toggled On!");
                myRobot.setConnectRequested(true);
            } else {
                // The toggle is disabled
                Log.d(TAG, "Connect button Toggled OFF.");
                myRobot.setConnectRequested(false);
            }
        }
    });

    if (nxtStatusMessageHandler == null)
        nxtStatusMessageHandler = new StatusMessageHandler();

    mStatusThread = new StatusThread(context, nxtStatusMessageHandler);
    mStatusThread.start();

    // Start the web service!
    Log.d(TAG, "Start web service here:");
    // Initiate message handler for web service
    if (robotWebServerMessageHandler == null)
        robotWebServerMessageHandler = new WebServerMessageHandler(this); // Has to include "this" to send context, see WebServerMessageHandler for explanation

    robotWebServer = new WebServer(context, PORT, robotWebServerMessageHandler, myRobot);

    try {
        robotWebServer.start();
    } catch (IOException e) {
        Log.d(TAG, "robotWebServer failed to start");
        //e.printStackTrace();
    }

    // TODO:
    /*
     * See this reference on how to rebuild this handler in onCreate if it is gone: http://stackoverflow.com/questions/18221593/android-handler-changing-weakreference
     */
    // TODO - Should I stop this thread in Destroy or some such place?

    Log.d(TAG, "Web service was started.");

}

From source file:org.petero.droidfish.activities.EditBoard.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case EDIT_DIALOG: {
        final int SIDE_TO_MOVE = 0;
        final int CLEAR_BOARD = 1;
        final int INITIAL_POS = 2;
        final int CASTLING_FLAGS = 3;
        final int EN_PASSANT_FILE = 4;
        final int MOVE_COUNTERS = 5;
        final int COPY_POSITION = 6;
        final int PASTE_POSITION = 7;
        final int GET_FEN = 8;

        List<CharSequence> lst = new ArrayList<CharSequence>();
        List<Integer> actions = new ArrayList<Integer>();
        lst.add(getString(R.string.side_to_move));
        actions.add(SIDE_TO_MOVE);/*  w w  w. j a  v a  2  s  .  c  o  m*/
        lst.add(getString(R.string.clear_board));
        actions.add(CLEAR_BOARD);
        lst.add(getString(R.string.initial_position));
        actions.add(INITIAL_POS);
        lst.add(getString(R.string.castling_flags));
        actions.add(CASTLING_FLAGS);
        lst.add(getString(R.string.en_passant_file));
        actions.add(EN_PASSANT_FILE);
        lst.add(getString(R.string.move_counters));
        actions.add(MOVE_COUNTERS);
        lst.add(getString(R.string.copy_position));
        actions.add(COPY_POSITION);
        lst.add(getString(R.string.paste_position));
        actions.add(PASTE_POSITION);
        if (DroidFish.hasFenProvider(getPackageManager())) {
            lst.add(getString(R.string.get_fen));
            actions.add(GET_FEN);
        }
        final List<Integer> finalActions = actions;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.edit_board);
        builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (finalActions.get(item)) {
                case SIDE_TO_MOVE:
                    showDialog(SIDE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case CLEAR_BOARD: {
                    Position pos = new Position();
                    cb.setPosition(pos);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                }
                case INITIAL_POS: {
                    try {
                        Position pos = TextIO.readFEN(TextIO.startPosFEN);
                        cb.setPosition(pos);
                        setSelection(-1);
                        checkValidAndUpdateMaterialDiff();
                    } catch (ChessParseError e) {
                    }
                    break;
                }
                case CASTLING_FLAGS:
                    removeDialog(CASTLE_DIALOG);
                    showDialog(CASTLE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case EN_PASSANT_FILE:
                    removeDialog(EP_DIALOG);
                    showDialog(EP_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case MOVE_COUNTERS:
                    removeDialog(MOVCNT_DIALOG);
                    showDialog(MOVCNT_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case COPY_POSITION: {
                    setPosFields();
                    String fen = TextIO.toFEN(cb.pos) + "\n";
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    clipboard.setText(fen);
                    setSelection(-1);
                    break;
                }
                case PASTE_POSITION: {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    if (clipboard.hasText()) {
                        String fen = clipboard.getText().toString();
                        setFEN(fen);
                    }
                    break;
                }
                case GET_FEN:
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.setType("application/x-chess-fen");
                    try {
                        startActivityForResult(i, RESULT_GET_FEN);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case SIDE_DIALOG: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_side_to_move_first);
        final int selectedItem = (cb.pos.whiteMove) ? 0 : 1;
        builder.setSingleChoiceItems(new String[] { getString(R.string.white), getString(R.string.black) },
                selectedItem, new Dialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (id == 0) { // white to move
                            cb.pos.setWhiteMove(true);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        } else {
                            cb.pos.setWhiteMove(false);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        return alert;
    }
    case CASTLE_DIALOG: {
        final CharSequence[] items = { getString(R.string.white_king_castle),
                getString(R.string.white_queen_castle), getString(R.string.black_king_castle),
                getString(R.string.black_queen_castle) };
        boolean[] checkedItems = { cb.pos.h1Castle(), cb.pos.a1Castle(), cb.pos.h8Castle(), cb.pos.a8Castle() };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.castling_flags);
        builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                Position pos = new Position(cb.pos);
                boolean a1Castle = pos.a1Castle();
                boolean h1Castle = pos.h1Castle();
                boolean a8Castle = pos.a8Castle();
                boolean h8Castle = pos.h8Castle();
                switch (which) {
                case 0:
                    h1Castle = isChecked;
                    break;
                case 1:
                    a1Castle = isChecked;
                    break;
                case 2:
                    h8Castle = isChecked;
                    break;
                case 3:
                    a8Castle = isChecked;
                    break;
                }
                int castleMask = 0;
                if (a1Castle)
                    castleMask |= 1 << Position.A1_CASTLE;
                if (h1Castle)
                    castleMask |= 1 << Position.H1_CASTLE;
                if (a8Castle)
                    castleMask |= 1 << Position.A8_CASTLE;
                if (h8Castle)
                    castleMask |= 1 << Position.H8_CASTLE;
                pos.setCastleMask(castleMask);
                cb.setPosition(pos);
                checkValidAndUpdateMaterialDiff();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case EP_DIALOG: {
        final CharSequence[] items = { "A", "B", "C", "D", "E", "F", "G", "H", getString(R.string.none) };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_en_passant_file);
        builder.setSingleChoiceItems(items, getEPFile(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                setEPFile(item);
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case MOVCNT_DIALOG: {
        View content = View.inflate(this, R.layout.edit_move_counters, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setView(content);
        builder.setTitle(R.string.edit_move_counters);
        final EditText halfMoveClock = (EditText) content.findViewById(R.id.ed_cnt_halfmove);
        final EditText fullMoveCounter = (EditText) content.findViewById(R.id.ed_cnt_fullmove);
        halfMoveClock.setText(String.format(Locale.US, "%d", cb.pos.halfMoveClock));
        fullMoveCounter.setText(String.format(Locale.US, "%d", cb.pos.fullMoveCounter));
        final Runnable setCounters = new Runnable() {
            public void run() {
                try {
                    int halfClock = Integer.parseInt(halfMoveClock.getText().toString());
                    int fullCount = Integer.parseInt(fullMoveCounter.getText().toString());
                    cb.pos.halfMoveClock = halfClock;
                    cb.pos.fullMoveCounter = fullCount;
                } catch (NumberFormatException nfe) {
                    Toast.makeText(getApplicationContext(), R.string.invalid_number_format, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        };
        builder.setPositiveButton("Ok", new Dialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setCounters.run();
            }
        });
        builder.setNegativeButton("Cancel", null);

        final Dialog dialog = builder.create();

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

From source file:com.neka.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from  ww  w.  ja v  a  2s .co m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            /*
            back.setText("<");
            */
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            //forward.setText(">");
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                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) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            //close.setText(buttonLabel);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                close.setBackgroundDrawable(closeIcon);
            } else {
                close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            //toolbar.addView(actionButtonContainer);
            //toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.chrynan.guitarchords.view.GuitarChordView.java

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    if (editable) {
        final InputConnectionAccomodatingLatinIMETypeNullIssues baseInputConnection = new InputConnectionAccomodatingLatinIMETypeNullIssues(
                this, false);
        outAttrs.actionLabel = null;//from   w  w  w .  j a v  a  2  s  .co  m
        outAttrs.inputType = InputType.TYPE_NULL;
        outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (editable) {
                    if (event
                            .getUnicodeChar() == (int) EditableAccomodatingLatinIMETypeNullIssues.ONE_UNPROCESSED_CHARACTER
                                    .charAt(0)) {
                        //We are ignoring this character, and we want everyone else to ignore it, too, so
                        // we return true indicating that we have handled it (by ignoring it).
                        return true;
                    }
                    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                        //Trap the Done key and close the keyboard if it is pressed (if that's what you want to do)
                        InputMethodManager imm = (InputMethodManager) getContext()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(GuitarChordView.this.getWindowToken(), 0);
                        if (touchEventMarker != null) {
                            Integer finger;
                            try {
                                finger = Integer.valueOf(baseInputConnection.getEditable().toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                                finger = touchEventMarker.getFinger();
                            }
                            touchEventMarker = new ChordMarker(touchEventMarker.getStartString(),
                                    touchEventMarker.getEndString(), touchEventMarker.getFret(), finger);
                            alertOnChordSelected(null, new ChordMarker(touchEventMarker),
                                    chord.contains(touchEventMarker));
                        }
                        return true;
                    }
                }
                return false;
            }
        });
        return baseInputConnection;
    }
    return null;
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

@Override
public boolean onEditorAction(final TextView view, final int actionId, final KeyEvent event) {
    if (event == null)
        return false;
    switch (event.getKeyCode()) {
    case KeyEvent.KEYCODE_ENTER: {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            send();/*w  w  w . jav a  2  s  . com*/
        }
        return true;
    }
    }
    return false;
}