List of usage examples for java.lang CharSequence charAt
char charAt(int index);
From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardBaseView.java
private CharSequence adjustCase(AnyKey key) { // if (mKeyboard.isShifted() && label != null && label.length() < 3 // && Character.isLowerCase(label.charAt(0))) { // label = label.toString().toUpperCase(); // }/*from ww w .ja v a2 s .c o m*/ CharSequence label = key.label; // if (mKeyboard.isShifted() && // (!TextUtils.isEmpty(label)) && // Character.isLowerCase(label.charAt(0))) { // label = label.toString().toUpperCase(); // } if (mKeyboard.isShifted()) { if (!TextUtils.isEmpty(key.shiftedKeyLabel)) label = key.shiftedKeyLabel; else if (!TextUtils.isEmpty(label) && Character.isLowerCase(label.charAt(0))) label = label.toString().toUpperCase(); } return label; }
From source file:com.httrack.android.HTTrackActivity.java
/** * We just entered in a new pane./*from w ww . j ava 2 s . c om*/ */ protected void onEnterNewPane() { switch (layouts[pane_id]) { case R.layout.activity_startup: final TextView text = TextView.class.cast(this.findViewById(R.id.fieldDisplay)); final TextView textDebug = TextView.class.cast(this.findViewById(R.id.fieldDebug)); // Welcome message. final String html = getString(R.string.welcome_message).replace("\n-", "\n").replace("\n", "<br />") .replace("HTTrack Website Copier", "<b>HTTrack Website Copier</b>"); text.setText(Html.fromHtml(html)); // Debugging and information. final StringBuilder str = new StringBuilder(); str.append("<i>"); if (version != null) { str.append("<br />Version: "); // Library version str.append(version); str.append(versionFeatures); // Android version str.append(" (Android version "); str.append(versionCode); str.append(")"); } // str.append(" Path: "); // str.append(getProjectRootFile().getAbsolutePath()); str.append(" IPv6: "); final InetAddress addrV6 = getIPv6Address(); str.append(addrV6 != null ? ("YES (" + addrV6.getHostAddress() + ")") : "NO"); str.append("</i>"); textDebug.setText(Html.fromHtml(str.toString())); // Enable or disable browse & cleanup button depending on existing // project(s) View.class.cast(this.findViewById(R.id.buttonClear)).setEnabled(hasProjectNames()); View.class.cast(this.findViewById(R.id.buttonBrowseAll)).setEnabled(hasProjectRootIndexFile()); break; case R.layout.activity_proj_name: // Refresh suggest refreshprojectNameSuggests(); /* Base path */ TextView.class.cast(findViewById(R.id.fieldBasePath)).setText(getProjectRootFile().getAbsolutePath()); // "Next" button is disabled if no project name is defined switchEmptyProjectName = !OptionsMapper.isStringNonEmpty(mapper.getProjectName()); View.class.cast(findViewById(R.id.buttonNext)).setEnabled(!switchEmptyProjectName); /* * Prior to Honeycomb (TODO FIXME: check that), the android browser is * unable to browse local file:// pages embedding spaces (%20 or +) * Therefore, warn the user. */ warnPreHoneycombSpaceIssue = android.os.Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB; /* Add text watcher for the "Next" button. */ final AutoCompleteTextView name = AutoCompleteTextView.class .cast(this.findViewById(R.id.fieldProjectName)); name.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { // Warn when seeing space if (warnPreHoneycombSpaceIssue) { for (int i = start; i < start + count; i++) { if (s.charAt(i) == ' ') { showNotification(getString(R.string.warning_space_in_filename), true); warnPreHoneycombSpaceIssue = false; break; } } } } @Override public void afterTextChanged(final Editable s) { // Enable/disable next button boolean empty = true; for (int i = 0; i < s.length(); i++) { if (Character.isLetterOrDigit(s.charAt(i))) { empty = false; break; } } if (empty != switchEmptyProjectName) { switchEmptyProjectName = empty; View.class.cast(findViewById(R.id.buttonNext)).setEnabled(!empty); } // (re) Set category final String category = getProjectCategory(s.toString()); TextView.class.cast(findViewById(R.id.fieldProjectCategory)) .setText(category != null ? category : ""); } // NOOP @Override public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } }); break; case R.layout.activity_proj_setup: // Existing cache ? final boolean hasProfile = hasCacheFile(); View.class.cast(this.findViewById(R.id.radioAction)).setEnabled(hasProfile); View.class.cast(this.findViewById(R.id.radioAction)) .setVisibility(hasProfile ? View.VISIBLE : View.GONE); if (hasProfile) { // Update is the default unless something was broken RadioGroup.class.cast(this.findViewById(R.id.radioAction)) .check(isInterruptedProfile() ? R.id.radioItemContinue : R.id.radioItemUpdate); } else { // Reset RadioGroup.class.cast(this.findViewById(R.id.radioAction)).check(-1); } break; case R.layout.activity_mirror_progress: setProgressLinesInternal(new String[] { getString(R.string.starting_worker_thread) }); startRunner(); if (runner != null) { ProgressBar.class.cast(findViewById(R.id.progressMirror)).setVisibility(View.VISIBLE); } break; case R.layout.activity_mirror_finished: // Ensure the engine has stopped running if (runner != null) { runner.stopMirror(true); } // Enable browse button if index.html exists final boolean hasIndex = hasTargetIndexFile(); View.class.cast(this.findViewById(R.id.buttonBrowse)).setEnabled(hasIndex); if (!hasIndex) { final File index = getTargetIndexFile(); Log.d(getClass().getSimpleName(), "no index found (" + (index != null ? index.getAbsolutePath() : "unknown location") + ")"); final String template = getString(R.string.no_index_html_in_xx); if (template == null) { throw new RuntimeException("R.string.no_index_html_in_xx is null"); } final File target = getTargetFile(); if (target != null) { final String warning = template.replace("%s", target.getPath()); showNotification(warning); } } // Enable logs if present final boolean hasLog = hasTargetLogFile(); View.class.cast(this.findViewById(R.id.buttonLogs)).setEnabled(hasLog); if (!hasLog) { final File log = getTargetLogFile(); Log.d(getClass().getSimpleName(), "no log found (" + (log != null ? log.getAbsolutePath() : "unknown location") + ")"); } // Final stats if (runner != null) { final HTTrackStats lastStats = runner.getLastStats(); if (lastStats != null && lastStats.errorsCount != 0) { // TODO } } break; } }
From source file:org.odk.collect.android.activities.FormEntryActivity.java
/** * Creates a view given the View type and an event * * @param advancingPage -- true if this results from advancing through the form * @return newly created View/* w w w .jav a 2s .c om*/ */ private View createView(int event, boolean advancingPage) { FormController formController = Collect.getInstance().getFormController(); if (hasHardwareMenu) { toolbar.setTitle(formController.getFormTitle()); } else { setTitle(formController.getFormTitle()); } switch (event) { case FormEntryController.EVENT_BEGINNING_OF_FORM: return createViewForFormBeginning(event, true, formController); case FormEntryController.EVENT_END_OF_FORM: View endView = View.inflate(this, R.layout.form_entry_end, null); ((TextView) endView.findViewById(R.id.description)) .setText(getString(R.string.save_enter_data_description, formController.getFormTitle())); // checkbox for if finished or ready to send final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished)); instanceComplete.setChecked(isInstanceComplete(true)); if (!adminPreferences.getBoolean(AdminKeys.KEY_MARK_AS_FINALIZED, true)) { instanceComplete.setVisibility(View.GONE); } // edittext to change the displayed name of the instance final EditText saveAs = (EditText) endView.findViewById(R.id.save_name); // disallow carriage returns in the name InputFilter returnFilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (Character.getType((source.charAt(i))) == Character.CONTROL) { return ""; } } return null; } }; saveAs.setFilters(new InputFilter[] { returnFilter }); String saveName = formController.getSubmissionMetadata().instanceName; if (saveName == null) { // no meta/instanceName field in the form -- see if we have a // name for this instance from a previous save attempt... if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance.getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } if (saveName == null) { // last resort, default to the form title saveName = formController.getFormTitle(); } // present the prompt to allow user to name the form TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.VISIBLE); saveAs.setText(saveName); saveAs.setEnabled(true); saveAs.setVisibility(View.VISIBLE); } else { // if instanceName is defined in form, this is the name -- no // revisions // display only the name, not the prompt, and disable edits TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); saveAs.setText(saveName); saveAs.setEnabled(false); saveAs.setVisibility(View.VISIBLE); } // override the visibility settings based upon admin preferences if (!adminPreferences.getBoolean(AdminKeys.KEY_SAVE_AS, true)) { saveAs.setVisibility(View.GONE); TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); } // Create 'save' button endView.findViewById(R.id.save_exit_button).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "createView.saveAndExit", instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete"); // Form is marked as 'saved' here. if (saveAs.getText().length() < 1) { ToastUtils.showShortToast(R.string.save_as_error); } else { saveDataToDisk(EXIT, instanceComplete.isChecked(), saveAs.getText().toString()); } } }); if (showNavigationButtons) { backButton.setEnabled(true); nextButton.setEnabled(false); } return endView; case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: case FormEntryController.EVENT_REPEAT: ODKView odkv = null; // should only be a group here if the event_group is a field-list try { FormEntryPrompt[] prompts = formController.getQuestionPrompts(); FormEntryCaption[] groups = formController.getGroupsForCurrentIndex(); odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage); Timber.i("Created view for group %s %s", (groups.length > 0 ? groups[groups.length - 1].getLongText() : "[top]"), (prompts.length > 0 ? prompts[0].getQuestionText() : "[no question]")); } catch (RuntimeException e) { Timber.e(e); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(e.getMessage(), DO_NOT_EXIT); } catch (JavaRosaException e1) { Timber.e(e1); createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT); } return createView(event, advancingPage); } // Makes a "clear answer" menu pop up on long-click for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly()) { // If it's a StringWidget register all its elements apart from EditText as // we want to enable paste option after long click on the EditText if (qw instanceof StringWidget) { for (int i = 0; i < qw.getChildCount(); i++) { if (!(qw.getChildAt(i) instanceof EditText)) { registerForContextMenu(qw.getChildAt(i)); } } } else { registerForContextMenu(qw); } } } if (showNavigationButtons) { adjustBackNavigationButtonVisibility(); nextButton.setEnabled(true); } return odkv; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); return new EmptyView(this); default: Timber.e("Attempted to create a view that does not exist."); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(getString(R.string.survey_internal_error), EXIT); } catch (JavaRosaException e) { Timber.e(e); createErrorDialog(e.getCause().getMessage(), EXIT); } return createView(event, advancingPage); } }
From source file:com.anysoftkeyboard.AnySoftKeyboard.java
private boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); // It is not exactly clear to me why, but sometimes, although I request // 1 character, I get // the entire text. This causes me to incorrectly detect restart // suggestions... if (!TextUtils.isEmpty(toLeft) && toLeft.length() == 1 && !isWordSeparator(toLeft.charAt(0))) { return true; }/*from w w w. ja va 2 s .c om*/ CharSequence toRight = ic.getTextAfterCursor(1, 0); return (!TextUtils.isEmpty(toRight)) && (toRight.length() == 1) && (!isWordSeparator(toRight.charAt(0))); }
From source file:com.Beat.RingdroidEditActivity.java
private String makeRingtoneFilename(CharSequence title, String extension) { String parentdir;/*from w w w . ja v a2 s .c o m*/ switch (mNewFileKind) { default: case FileSaveDialog.FILE_KIND_MUSIC: parentdir = "/sdcard/media/audio/music"; break; case FileSaveDialog.FILE_KIND_ALARM: parentdir = "/sdcard/media/audio/alarms"; break; case FileSaveDialog.FILE_KIND_NOTIFICATION: parentdir = "/sdcard/media/audio/notifications"; break; case FileSaveDialog.FILE_KIND_RINGTONE: parentdir = "/sdcard/media/audio/ringtones"; break; } // Create the parent directory File parentDirFile = new File(parentdir); parentDirFile.mkdirs(); // If we can't write to that special path, try just writing // directly to the sdcard if (!parentDirFile.isDirectory()) { parentdir = "/sdcard"; } // Turn the title into a filename String filename = ""; for (int i = 0; i < title.length(); i++) { if (Character.isLetterOrDigit(title.charAt(i))) { filename += title.charAt(i); } } // Try to make the filename unique String path = null; for (int i = 0; i < 100; i++) { String testPath; if (i > 0) testPath = parentdir + "/" + filename + i + extension; else testPath = parentdir + "/" + filename + extension; try { RandomAccessFile f = new RandomAccessFile(new File(testPath), "r"); } catch (Exception e) { // Good, the file didn't exist path = testPath; break; } } return path; }
From source file:com.yek.keyboard.anysoftkeyboard.AnySoftKeyboard.java
private void onFunctionKey(final int primaryCode, final Keyboard.Key key, final int multiTapIndex, final int[] nearByKeyCodes, final boolean fromUI) { if (BuildConfig.DEBUG) Logger.d(TAG, "onFunctionKey %d", primaryCode); final InputConnection ic = getCurrentInputConnection(); switch (primaryCode) { case KeyCodes.DELETE: if (ic == null)// if we don't want to do anything, lets check null first. break; // we do backword if the shift is pressed while pressing // backspace (like in a PC) if (mAskPrefs.useBackword() && mShiftKeyState.isPressed() && !mShiftKeyState.isLocked()) { handleBackWord(ic);//from w w w . j a v a2s .com } else { handleDeleteLastCharacter(false); } break; case KeyCodes.SHIFT: if (fromUI) { handleShift(); } else { //not from UI (user not actually pressed that button) onPress(primaryCode); onRelease(primaryCode); } break; case KeyCodes.SHIFT_LOCK: mShiftKeyState.toggleLocked(); handleShift(); break; case KeyCodes.DELETE_WORD: if (ic == null)// if we don't want to do anything, lets check // null first. break; handleBackWord(ic); break; case KeyCodes.CLEAR_INPUT: if (ic != null) { ic.beginBatchEdit(); abortCorrectionAndResetPredictionState(false); ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE); ic.endBatchEdit(); } break; case KeyCodes.CTRL: if (fromUI) { handleControl(); } else { //not from UI (user not actually pressed that button) onPress(primaryCode); onRelease(primaryCode); } break; case KeyCodes.CTRL_LOCK: mControlKeyState.toggleLocked(); handleControl(); break; case KeyCodes.ARROW_LEFT: case KeyCodes.ARROW_RIGHT: final int keyEventKeyCode = primaryCode == KeyCodes.ARROW_LEFT ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT; if (!handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition)) { sendDownUpKeyEvents(keyEventKeyCode); } break; case KeyCodes.ARROW_UP: sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP); break; case KeyCodes.ARROW_DOWN: sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN); break; case KeyCodes.MOVE_HOME: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { sendDownUpKeyEvents(0x0000007a/*API 11:KeyEvent.KEYCODE_MOVE_HOME*/); } else { if (ic != null) { CharSequence textBefore = ic.getTextBeforeCursor(1024, 0); if (!TextUtils.isEmpty(textBefore)) { int newPosition = textBefore.length() - 1; while (newPosition > 0) { char chatAt = textBefore.charAt(newPosition - 1); if (chatAt == '\n' || chatAt == '\r') { break; } newPosition--; } if (newPosition < 0) newPosition = 0; ic.setSelection(newPosition, newPosition); } } } break; case KeyCodes.MOVE_END: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //API 11: KeyEvent.KEYCODE_MOVE_END sendDownUpKeyEvents(0x0000007b); } else { if (ic != null) { CharSequence textAfter = ic.getTextAfterCursor(1024, 0); if (!TextUtils.isEmpty(textAfter)) { int newPosition = 1; while (newPosition < textAfter.length()) { char chatAt = textAfter.charAt(newPosition); if (chatAt == '\n' || chatAt == '\r') { break; } newPosition++; } if (newPosition > textAfter.length()) newPosition = textAfter.length(); try { CharSequence textBefore = ic.getTextBeforeCursor(Integer.MAX_VALUE, 0); if (!TextUtils.isEmpty(textBefore)) { newPosition = newPosition + textBefore.length(); } ic.setSelection(newPosition, newPosition); } catch (Throwable e/*I'm using Integer.MAX_VALUE, it's scary.*/) { Logger.w(TAG, "Failed to getTextBeforeCursor.", e); } } } } break; case KeyCodes.VOICE_INPUT: if (mVoiceRecognitionTrigger.isInstalled()) { mVoiceRecognitionTrigger .startVoiceRecognition(getCurrentAlphabetKeyboard().getDefaultDictionaryLocale()); } else { Intent voiceInputNotInstalledIntent = new Intent(getApplicationContext(), VoiceInputNotInstalledActivity.class); voiceInputNotInstalledIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(voiceInputNotInstalledIntent); } break; case KeyCodes.CANCEL: handleClose(); break; case KeyCodes.SETTINGS: showOptionsMenu(); break; case KeyCodes.SPLIT_LAYOUT: case KeyCodes.MERGE_LAYOUT: case KeyCodes.COMPACT_LAYOUT_TO_RIGHT: case KeyCodes.COMPACT_LAYOUT_TO_LEFT: if (getInputView() != null) { mKeyboardInCondensedMode = CondenseType.fromKeyCode(primaryCode); setKeyboardForView(getCurrentKeyboard()); } break; case KeyCodes.DOMAIN: onText(key, mAskPrefs.getDomainText()); break; case KeyCodes.QUICK_TEXT: onQuickTextRequested(key); break; case KeyCodes.QUICK_TEXT_POPUP: onQuickTextKeyboardRequested(key); break; case KeyCodes.MODE_SYMOBLS: nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Symbols); break; case KeyCodes.MODE_ALPHABET: if (getKeyboardSwitcher().shouldPopupForLanguageSwitch()) { showLanguageSelectionDialog(); } else { nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Alphabet); } break; case KeyCodes.UTILITY_KEYBOARD: getInputView().openUtilityKeyboard(); break; case KeyCodes.MODE_ALPHABET_POPUP: showLanguageSelectionDialog(); break; case KeyCodes.ALT: nextAlterKeyboard(getCurrentInputEditorInfo()); break; case KeyCodes.KEYBOARD_CYCLE: nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.Any); break; case KeyCodes.KEYBOARD_REVERSE_CYCLE: nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.PreviousAny); break; case KeyCodes.KEYBOARD_CYCLE_INSIDE_MODE: nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.AnyInsideMode); break; case KeyCodes.KEYBOARD_MODE_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), KeyboardSwitcher.NextKeyboardType.OtherMode); break; case KeyCodes.CLIPBOARD_COPY: case KeyCodes.CLIPBOARD_PASTE: case KeyCodes.CLIPBOARD_CUT: case KeyCodes.CLIPBOARD_SELECT_ALL: case KeyCodes.CLIPBOARD_PASTE_POPUP: case KeyCodes.CLIPBOARD_SELECT: handleClipboardOperation(key, primaryCode, ic); //not allowing undo on-text in clipboard paste operations. if (primaryCode == KeyCodes.CLIPBOARD_PASTE) mCommittedWord = ""; break; default: if (BuildConfig.DEBUG) { //this should not happen! We should handle ALL function keys. throw new RuntimeException("UNHANDLED FUNCTION KEY! primary code " + primaryCode); } else { Logger.w(TAG, "UNHANDLED FUNCTION KEY! primary code %d. Ignoring.", primaryCode); } } }
From source file:com.anysoftkeyboard.AnySoftKeyboard.java
private void onFunctionKey(final int primaryCode, final Key key, final int multiTapIndex, final int[] nearByKeyCodes, final boolean fromUI) { if (BuildConfig.DEBUG) Logger.d(TAG, "onFunctionKey %d", primaryCode); final InputConnection ic = getCurrentInputConnection(); switch (primaryCode) { case KeyCodes.DELETE: if (ic == null)// if we don't want to do anything, lets check null first. break; // we do backword if the shift is pressed while pressing // backspace (like in a PC) if (mAskPrefs.useBackword() && mShiftKeyState.isPressed() && !mShiftKeyState.isLocked()) { handleBackWord(ic);/* w w w. ja va 2s .co m*/ } else { handleDeleteLastCharacter(false); } break; case KeyCodes.SHIFT: if (fromUI) { handleShift(); } else { //not from UI (user not actually pressed that button) onPress(primaryCode); onRelease(primaryCode); } break; case KeyCodes.SHIFT_LOCK: mShiftKeyState.toggleLocked(); handleShift(); break; case KeyCodes.DELETE_WORD: if (ic == null)// if we don't want to do anything, lets check // null first. break; handleBackWord(ic); break; case KeyCodes.CLEAR_INPUT: if (ic != null) { ic.beginBatchEdit(); abortCorrectionAndResetPredictionState(false); ic.deleteSurroundingText(Integer.MAX_VALUE, Integer.MAX_VALUE); ic.endBatchEdit(); } break; case KeyCodes.CTRL: if (fromUI) { handleControl(); } else { //not from UI (user not actually pressed that button) onPress(primaryCode); onRelease(primaryCode); } break; case KeyCodes.CTRL_LOCK: mControlKeyState.toggleLocked(); handleControl(); break; case KeyCodes.ARROW_LEFT: case KeyCodes.ARROW_RIGHT: final int keyEventKeyCode = primaryCode == KeyCodes.ARROW_LEFT ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT; if (!handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition)) { sendDownUpKeyEvents(keyEventKeyCode); } break; case KeyCodes.ARROW_UP: sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP); break; case KeyCodes.ARROW_DOWN: sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN); break; case KeyCodes.MOVE_HOME: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { sendDownUpKeyEvents(0x0000007a/*API 11:KeyEvent.KEYCODE_MOVE_HOME*/); } else { if (ic != null) { CharSequence textBefore = ic.getTextBeforeCursor(1024, 0); if (!TextUtils.isEmpty(textBefore)) { int newPosition = textBefore.length() - 1; while (newPosition > 0) { char chatAt = textBefore.charAt(newPosition - 1); if (chatAt == '\n' || chatAt == '\r') { break; } newPosition--; } if (newPosition < 0) newPosition = 0; ic.setSelection(newPosition, newPosition); } } } break; case KeyCodes.MOVE_END: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //API 11: KeyEvent.KEYCODE_MOVE_END sendDownUpKeyEvents(0x0000007b); } else { if (ic != null) { CharSequence textAfter = ic.getTextAfterCursor(1024, 0); if (!TextUtils.isEmpty(textAfter)) { int newPosition = 1; while (newPosition < textAfter.length()) { char chatAt = textAfter.charAt(newPosition); if (chatAt == '\n' || chatAt == '\r') { break; } newPosition++; } if (newPosition > textAfter.length()) newPosition = textAfter.length(); try { CharSequence textBefore = ic.getTextBeforeCursor(Integer.MAX_VALUE, 0); if (!TextUtils.isEmpty(textBefore)) { newPosition = newPosition + textBefore.length(); } ic.setSelection(newPosition, newPosition); } catch (Throwable e/*I'm using Integer.MAX_VALUE, it's scary.*/) { Logger.w(TAG, "Failed to getTextBeforeCursor.", e); } } } } break; case KeyCodes.VOICE_INPUT: if (mVoiceRecognitionTrigger.isInstalled()) { mVoiceRecognitionTrigger .startVoiceRecognition(getCurrentAlphabetKeyboard().getDefaultDictionaryLocale()); } else { Intent voiceInputNotInstalledIntent = new Intent(getApplicationContext(), VoiceInputNotInstalledActivity.class); voiceInputNotInstalledIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(voiceInputNotInstalledIntent); } break; case KeyCodes.CANCEL: hideWindow(); break; case KeyCodes.SETTINGS: showOptionsMenu(); break; case KeyCodes.SPLIT_LAYOUT: case KeyCodes.MERGE_LAYOUT: case KeyCodes.COMPACT_LAYOUT_TO_RIGHT: case KeyCodes.COMPACT_LAYOUT_TO_LEFT: if (getInputView() != null) { mKeyboardInCondensedMode = CondenseType.fromKeyCode(primaryCode); setKeyboardForView(getCurrentKeyboard()); } break; case KeyCodes.DOMAIN: onText(key, mAskPrefs.getDomainText()); break; case KeyCodes.QUICK_TEXT: onQuickTextRequested(key); break; case KeyCodes.QUICK_TEXT_POPUP: onQuickTextKeyboardRequested(key); break; case KeyCodes.MODE_SYMOBLS: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Symbols); break; case KeyCodes.MODE_ALPHABET: if (getKeyboardSwitcher().shouldPopupForLanguageSwitch()) { showLanguageSelectionDialog(); } else { nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Alphabet); } break; case KeyCodes.UTILITY_KEYBOARD: getInputView().openUtilityKeyboard(); break; case KeyCodes.MODE_ALPHABET_POPUP: showLanguageSelectionDialog(); break; case KeyCodes.ALT: nextAlterKeyboard(getCurrentInputEditorInfo()); break; case KeyCodes.KEYBOARD_CYCLE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.Any); break; case KeyCodes.KEYBOARD_REVERSE_CYCLE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.PreviousAny); break; case KeyCodes.KEYBOARD_CYCLE_INSIDE_MODE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.AnyInsideMode); break; case KeyCodes.KEYBOARD_MODE_CHANGE: nextKeyboard(getCurrentInputEditorInfo(), NextKeyboardType.OtherMode); break; case KeyCodes.CLIPBOARD_COPY: case KeyCodes.CLIPBOARD_PASTE: case KeyCodes.CLIPBOARD_CUT: case KeyCodes.CLIPBOARD_SELECT_ALL: case KeyCodes.CLIPBOARD_PASTE_POPUP: case KeyCodes.CLIPBOARD_SELECT: handleClipboardOperation(key, primaryCode, ic); //not allowing undo on-text in clipboard paste operations. if (primaryCode == KeyCodes.CLIPBOARD_PASTE) mCommittedWord = ""; break; default: if (BuildConfig.DEBUG) { //this should not happen! We should handle ALL function keys. throw new RuntimeException("UNHANDLED FUNCTION KEY! primary code " + primaryCode); } else { Logger.w(TAG, "UNHANDLED FUNCTION KEY! primary code %d. Ignoring.", primaryCode); } } }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Encodes a text value, possibly compressing. *///from w w w.j a v a 2 s . c o m private ByteBuffer encodeTextValue(Object obj, int minChars, int maxChars, boolean forceUncompressed) throws IOException { CharSequence text = toCharSequence(obj); if ((text.length() > maxChars) || (text.length() < minChars)) { throw new IOException("Text is wrong length for " + getType() + " column, max " + maxChars + ", min " + minChars + ", got " + text.length()); } // may only compress if column type allows it if (!forceUncompressed && isCompressedUnicode()) { // for now, only do very simple compression (only compress text which is // all ascii text) if (isAsciiCompressible(text)) { byte[] encodedChars = new byte[TEXT_COMPRESSION_HEADER.length + text.length()]; encodedChars[0] = TEXT_COMPRESSION_HEADER[0]; encodedChars[1] = TEXT_COMPRESSION_HEADER[1]; for (int i = 0; i < text.length(); ++i) { encodedChars[i + TEXT_COMPRESSION_HEADER.length] = (byte) text.charAt(i); } return ByteBuffer.wrap(encodedChars); } } return encodeUncompressedText(text, getCharset()); }
From source file:com.kll.collect.android.activities.FormEntryActivity.java
/** * Creates a view given the View type and an event * * @param event//from ww w . j av a 2s .co m * @param advancingPage * -- true if this results from advancing through the form * @return newly created View */ private View createView(int event, boolean advancingPage, int swipeCase) { FormController formController = Collect.getInstance().getFormController(); /* setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle());*/ int questioncount = formController.getFormDef().getDeepChildCount(); switch (event) { case FormEntryController.EVENT_BEGINNING_OF_FORM: progressValue = 0.0; progressUpdate(progressValue, questioncount); View startView = View.inflate(this, R.layout.form_entry_start, null); /*setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle());*/ Drawable image = null; File mediaFolder = formController.getMediaFolder(); String mediaDir = mediaFolder.getAbsolutePath(); BitmapDrawable bitImage = null; // attempt to load the form-specific logo... // this is arbitrarily silly bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator + "form_logo.png"); if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) { image = bitImage; } if (image == null) { // show the opendatakit zig... // image = // getResources().getDrawable(R.drawable.opendatakit_zig); ((ImageView) startView.findViewById(R.id.form_start_bling)).setVisibility(View.GONE); } else { ImageView v = ((ImageView) startView.findViewById(R.id.form_start_bling)); v.setImageDrawable(image); v.setContentDescription(formController.getFormTitle()); } // change start screen based on navigation prefs String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this) .getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean useSwipe = false; Boolean useButtons = false; ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance)); ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup)); TextView ta = ((TextView) startView.findViewById(R.id.text_advance)); TextView tb = ((TextView) startView.findViewById(R.id.text_backup)); TextView d = ((TextView) startView.findViewById(R.id.description)); if (navigationChoice != null) { if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) { useSwipe = true; } if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { useButtons = true; } } if (useSwipe && !useButtons) { d.setText(getString(R.string.swipe_instructions, formController.getFormTitle())); } else if (useButtons && !useSwipe) { ia.setVisibility(View.GONE); ib.setVisibility(View.GONE); ta.setVisibility(View.GONE); tb.setVisibility(View.GONE); d.setText(getString(R.string.buttons_instructions, formController.getFormTitle())); } else { d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle())); } if (mBackButton.isShown()) { mBackButton.setEnabled(false); } if (mNextButton.isShown()) { mNextButton.setEnabled(true); } return startView; case FormEntryController.EVENT_END_OF_FORM: progressValue = questioncount; progressUpdate(progressValue, questioncount); View endView = View.inflate(this, R.layout.form_entry_end, null); ((ImageView) endView.findViewById(R.id.completed)) .setImageDrawable(getResources().getDrawable(R.drawable.complete_tick)); ((TextView) endView.findViewById(R.id.description)) .setText(getString(R.string.save_enter_data_description, formController.getFormTitle())); // checkbox for if finished or ready to send final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished)); instanceComplete.setChecked(isInstanceComplete(true)); if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) { instanceComplete.setVisibility(View.GONE); } // edittext to change the displayed name of the instance final EditText saveAs = (EditText) endView.findViewById(R.id.save_name); // disallow carriage returns in the name InputFilter returnFilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (Character.getType((source.charAt(i))) == Character.CONTROL) { return ""; } } return null; } }; saveAs.setFilters(new InputFilter[] { returnFilter }); String saveName = getSaveName(); if (saveName == null) { // no meta/instanceName field in the form -- see if we have a // name for this instance from a previous save attempt... if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance.getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } if (saveName == null) { // last resort, default to the form title saveName = formController.getFormTitle(); } // present the prompt to allow user to name the form TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.VISIBLE); saveAs.setText(saveName); saveAs.setEnabled(true); saveAs.setVisibility(View.VISIBLE); } else { // if instanceName is defined in form, this is the name -- no // revisions // display only the name, not the prompt, and disable edits TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); saveAs.setText(saveName); saveAs.setEnabled(false); saveAs.setBackgroundColor(Color.WHITE); saveAs.setVisibility(View.VISIBLE); } // override the visibility settings based upon admin preferences if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_AS, true)) { saveAs.setVisibility(View.GONE); TextView sa = (TextView) endView.findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); } // Create 'save' button ((Button) endView.findViewById(R.id.save_exit_button)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "createView.saveAndExit", instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete"); // Form is marked as 'saved' here. if (saveAs.getText().length() < 1) { Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show(); } else { saveDataToDisk(EXIT, instanceComplete.isChecked(), saveAs.getText().toString()); } } }); if (mBackButton.isShown()) { mBackButton.setEnabled(true); } if (mNextButton.isShown()) { mNextButton.setEnabled(false); } return endView; case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: case FormEntryController.EVENT_REPEAT: ODKView odkv = null; // should only be a group here if the event_group is a field-list try { double depth = (double) formController.getFormIndex().getDepth(); double local_index = (double) formController.getFormIndex().getLocalIndex(); double instance_index = (double) formController.getFormIndex().getInstanceIndex(); Log.i("Question coint", Integer.toString(questioncount)); Log.i("Depth", Integer.toString(formController.getFormIndex().getDepth())); Log.i("Local Index", Integer.toString(formController.getFormIndex().getLocalIndex())); Log.i("Instance Index", Integer.toString(formController.getFormIndex().getInstanceIndex())); if (swipeCase == NEXT) { Log.i("progressValue", Double.toString(progressValue)); } if (swipeCase == PREVIOUS) { progressValue = progressValue - (1 - (instance_index * local_index / questioncount * depth)); Log.i("progressValue", Double.toString(progressValue)); } Log.i("progressValue", Double.toString(progressValue)); progressUpdate(progressValue, questioncount); FormEntryPrompt[] prompts = formController.getQuestionPrompts(); FormEntryCaption[] groups = formController.getGroupsForCurrentIndex(); odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage); Log.i(t, "created view for group " + (groups.length > 0 ? groups[groups.length - 1].getLongText() : "[top]") + " " + (prompts.length > 0 ? prompts[0].getQuestionText() : "[no question]")); } catch (RuntimeException e) { Log.e(t, e.getMessage(), e); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(e.getMessage(), DO_NOT_EXIT); } catch (JavaRosaException e1) { Log.e(t, e1.getMessage(), e1); createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT); } return createView(event, advancingPage, swipeCase); } // Makes a "clear answer" menu pop up on long-click for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly()) { registerForContextMenu(qw); } } if (mBackButton.isShown() && mNextButton.isShown()) { mBackButton.setEnabled(true); mNextButton.setEnabled(true); } return odkv; default: Log.e(t, "Attempted to create a view that does not exist."); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(getString(R.string.survey_internal_error), EXIT); } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), EXIT); } return createView(event, advancingPage, swipeCase); } }
From source file:org.distantshoresmedia.keyboard.LatinIME.java
private void removeTrailingSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return;/*www.j av a 2s. com*/ CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == ASCII_SPACE) { ic.deleteSurroundingText(1, 0); } }