List of usage examples for android.content.res Resources getString
@NonNull public String getString(@StringRes int id) throws NotFoundException
From source file:com.tct.emailcommon.provider.EmailContent.java
public static synchronized void init(Context context) { if (AUTHORITY == null) { final Resources res = context.getResources(); EMAIL_PACKAGE_NAME = res.getString(R.string.email_package_name); AUTHORITY = EMAIL_PACKAGE_NAME + ".provider"; LogUtils.d("EmailContent", "init for " + AUTHORITY); NOTIFIER_AUTHORITY = EMAIL_PACKAGE_NAME + ".notifier"; CONTENT_URI = Uri.parse("content://" + AUTHORITY); CONTENT_NOTIFIER_URI = Uri.parse("content://" + NOTIFIER_AUTHORITY); PICK_TRASH_FOLDER_URI = Uri.parse("content://" + AUTHORITY + "/pickTrashFolder"); PICK_SENT_FOLDER_URI = Uri.parse("content://" + AUTHORITY + "/pickSentFolder"); MAILBOX_NOTIFICATION_URI = Uri.parse("content://" + AUTHORITY + "/mailboxNotification"); MAILBOX_MOST_RECENT_MESSAGE_URI = Uri.parse("content://" + AUTHORITY + "/mailboxMostRecentMessage"); MAILBOX_MOST_RECENT_UNREAD_MESSAGE_URI = Uri .parse("content://" + AUTHORITY + "/mailboxMostRecentUnread"); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247 ADD ACCOUNT_CHECK_URI = Uri.parse("content://" + AUTHORITY + "/accountCheck"); PROVIDER_PERMISSION = EMAIL_PACKAGE_NAME + ".permission.ACCESS_PROVIDER"; // Initialize subclasses Account.initAccount();/*w w w. j a v a 2s.co m*/ Mailbox.initMailbox(); QuickResponse.initQuickResponse(); HostAuth.initHostAuth(); Credential.initCredential(); Policy.initPolicy(); Message.initMessage(); MessageMove.init(); MessageStateChange.init(); Body.initBody(); Attachment.initAttachment(); } }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundLoadTutorial(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundLoadTutorial"); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); Collection col = params[0].getCollection(); col.getDb().getDatabase().beginTransaction(); String title = res.getString(R.string.help_tutorial); try {/*from www. ja v a 2 s. co m*/ // get deck or create it long did = col.getDecks().id(title); // reset todays counts JSONObject d = col.getDecks().get(did); for (String t : new String[] { "new", "rev", "lrn", "time" }) { String k = t + "Today"; JSONArray ja = new JSONArray(); ja.put(col.getSched().getToday()); ja.put(0); d.put(k, ja); } // save deck col.getDecks().save(d); if (col.getSched().cardCount("(" + did + ")") > 0) { // deck does already exist. Remove all cards and recreate them // to ensure the correct order col.remCards(col.getDecks().cids(did)); } JSONObject model = col.getModels().byName(title); // TODO: check, if model is valid or delete and recreate it // TODO: deactivated at the moment as if forces a schema change // create model (remove old ones first) // while (model != null) { // JSONObject m = col.getModels().byName(title); // // rename old tutorial model if there are some non tutorial cards // in it // if // (col.getDb().queryScalar("SELECT id FROM cards WHERE nid IN (SELECT id FROM notes WHERE mid = " // + // m.getLong("id") + ")", false) == 0) { // col.getModels().rem(m); // } else { // m.put("name", title + " (renamed)"); // col.getModels().save(m); // } // } if (model == null) { model = col.getModels().addBasicModel(col, title); } model.put("did", did); String[] questions = res.getStringArray(R.array.tutorial_questions); String[] answers = res.getStringArray(R.array.tutorial_answers); String[] sampleQuestions = res.getStringArray(R.array.tutorial_capitals_questions); String[] sampleAnswers = res.getStringArray(R.array.tutorial_capitals_answers); int len = Math.min(questions.length, answers.length); for (int i = 0; i < len + Math.min(sampleQuestions.length, sampleAnswers.length); i++) { Note note = col.newNote(model); if (note.values().length < 2) { return new TaskData(false); } note.values()[0] = (i < len) ? questions[i] : sampleQuestions[i - len]; note.values()[1] = (i < len) ? answers[i] : sampleAnswers[i - len]; col.addNote(note); } // deck.setSessionTimeLimit(0); if (col.getSched().cardCount("(" + did + ")") == 0) { // error, delete deck col.getDecks().rem(did, true); return new TaskData(false); } else { col.save(); col.getDecks().select(did); col.getDb().getDatabase().setTransactionSuccessful(); return new TaskData(true); } } catch (SQLException e) { AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial"); return new DeckTask.TaskData(false); } catch (JSONException e) { AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial"); return new DeckTask.TaskData(false); } finally { col.getDb().getDatabase().endTransaction(); } }
From source file:com.bw.luzz.monkeyapplication.View.DateTimePicker.time.TimePickerDialog.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mdtp_time_picker_dialog, container, false); KeyboardListener keyboardListener = new KeyboardListener(); view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener); // If an accent color has not been set manually, get it from the context if (mAccentColor == -1) { mAccentColor = Utils.getAccentColorFromThemeIfAvailable(getActivity()); }/*from w w w . java2 s. c o m*/ // if theme mode has not been set by java code, check if it is specified in Style.xml if (!mThemeDarkChanged) { mThemeDark = Utils.isDarkTheme(getActivity(), mThemeDark); } Resources res = getResources(); Context context = getActivity(); mHourPickerDescription = res.getString(R.string.mdtp_hour_picker_description); mSelectHours = res.getString(R.string.mdtp_select_hours); mMinutePickerDescription = res.getString(R.string.mdtp_minute_picker_description); mSelectMinutes = res.getString(R.string.mdtp_select_minutes); mSecondPickerDescription = res.getString(R.string.mdtp_second_picker_description); mSelectSeconds = res.getString(R.string.mdtp_select_seconds); mSelectedColor = ContextCompat.getColor(context, R.color.mdtp_white); mUnselectedColor = ContextCompat.getColor(context, R.color.mdtp_accent_color_focused); mHourView = (TextView) view.findViewById(R.id.hours); mHourView.setOnKeyListener(keyboardListener); mHourSpaceView = (TextView) view.findViewById(R.id.hour_space); mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space); mMinuteView = (TextView) view.findViewById(R.id.minutes); mMinuteView.setOnKeyListener(keyboardListener); mSecondSpaceView = (TextView) view.findViewById(R.id.seconds_space); mSecondView = (TextView) view.findViewById(R.id.seconds); mSecondView.setOnKeyListener(keyboardListener); mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label); mAmPmTextView.setOnKeyListener(keyboardListener); String[] amPmTexts = new DateFormatSymbols().getAmPmStrings(); mAmText = amPmTexts[0]; mPmText = amPmTexts[1]; mHapticFeedbackController = new HapticFeedbackController(getActivity()); mInitialTime = roundToNearest(mInitialTime); mTimePicker = (RadialPickerLayout) view.findViewById(R.id.time_picker); mTimePicker.setOnValueSelectedListener(this); mTimePicker.setOnKeyListener(keyboardListener); mTimePicker.initialize(getActivity(), this, mInitialTime, mIs24HourMode); int currentItemShowing = HOUR_INDEX; if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) { currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING); } setCurrentItemShowing(currentItemShowing, false, true, true); mTimePicker.invalidate(); mHourView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setCurrentItemShowing(HOUR_INDEX, true, false, true); tryVibrate(); } }); mMinuteView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setCurrentItemShowing(MINUTE_INDEX, true, false, true); tryVibrate(); } }); mSecondView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { setCurrentItemShowing(SECOND_INDEX, true, false, true); tryVibrate(); } }); mOkButton = (Button) view.findViewById(R.id.ok); mOkButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mInKbMode && isTypedTimeFullyLegal()) { finishKbMode(false); } else { tryVibrate(); } notifyOnDateListener(); dismiss(); } }); mOkButton.setOnKeyListener(keyboardListener); mOkButton.setTypeface(TypefaceHelper.get(context, "Roboto-Medium")); if (mOkString != null) mOkButton.setText(mOkString); else mOkButton.setText(mOkResid); mCancelButton = (Button) view.findViewById(R.id.cancel); mCancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { tryVibrate(); if (getDialog() != null) getDialog().cancel(); } }); mCancelButton.setTypeface(TypefaceHelper.get(context, "Roboto-Medium")); if (mCancelString != null) mCancelButton.setText(mCancelString); else mCancelButton.setText(mCancelResid); mCancelButton.setVisibility(isCancelable() ? View.VISIBLE : View.GONE); // Enable or disable the AM/PM view. mAmPmHitspace = view.findViewById(R.id.ampm_hitspace); if (mIs24HourMode) { mAmPmTextView.setVisibility(View.GONE); } else { mAmPmTextView.setVisibility(View.VISIBLE); updateAmPmDisplay(mInitialTime.isAM() ? AM : PM); mAmPmHitspace.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Don't do anything if either AM or PM are disabled if (isAmDisabled() || isPmDisabled()) return; tryVibrate(); int amOrPm = mTimePicker.getIsCurrentlyAmOrPm(); if (amOrPm == AM) { amOrPm = PM; } else if (amOrPm == PM) { amOrPm = AM; } mTimePicker.setAmOrPm(amOrPm); } }); } // Disable seconds picker if (!mEnableSeconds) { mSecondSpaceView.setVisibility(View.GONE); view.findViewById(R.id.separator_seconds).setVisibility(View.GONE); } // Center stuff depending on what's visible if (mIs24HourMode && !mEnableSeconds) { // center first separator RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT); TextView separatorView = (TextView) view.findViewById(R.id.separator); separatorView.setLayoutParams(paramsSeparator); } else if (mEnableSeconds) { // link separator to minutes final View separator = view.findViewById(R.id.separator); RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); paramsSeparator.addRule(RelativeLayout.LEFT_OF, R.id.minutes_space); paramsSeparator.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); separator.setLayoutParams(paramsSeparator); if (!mIs24HourMode) { // center minutes RelativeLayout.LayoutParams paramsMinutes = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); paramsMinutes.addRule(RelativeLayout.CENTER_IN_PARENT); mMinuteSpaceView.setLayoutParams(paramsMinutes); } else { // move minutes to right of center RelativeLayout.LayoutParams paramsMinutes = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); paramsMinutes.addRule(RelativeLayout.RIGHT_OF, R.id.center_view); mMinuteSpaceView.setLayoutParams(paramsMinutes); } } mAllowAutoAdvance = true; setHour(mInitialTime.getHour(), true); setMinute(mInitialTime.getMinute()); setSecond(mInitialTime.getSecond()); // Set up for keyboard mode. mDoublePlaceholderText = res.getString(R.string.mdtp_time_placeholder); mDeletedKeyFormat = res.getString(R.string.mdtp_deleted_key); mPlaceholderText = mDoublePlaceholderText.charAt(0); mAmKeyCode = mPmKeyCode = -1; generateLegalTimesTree(); if (mInKbMode) { mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES); tryStartingKbMode(-1); mHourView.invalidate(); } else if (mTypedTimes == null) { mTypedTimes = new ArrayList<>(); } // Set the title (if any) TextView timePickerHeader = (TextView) view.findViewById(R.id.time_picker_header); if (!mTitle.isEmpty()) { timePickerHeader.setVisibility(TextView.VISIBLE); timePickerHeader.setText(mTitle.toUpperCase(Locale.getDefault())); } // Set the theme at the end so that the initialize()s above don't counteract the theme. mOkButton.setTextColor(mAccentColor); mCancelButton.setTextColor(mAccentColor); timePickerHeader.setBackgroundColor(Utils.darkenColor(mAccentColor)); view.findViewById(R.id.time_display_background).setBackgroundColor(mAccentColor); view.findViewById(R.id.time_display).setBackgroundColor(mAccentColor); if (getDialog() == null) { view.findViewById(R.id.done_background).setVisibility(View.GONE); } int circleBackground = ContextCompat.getColor(context, R.color.mdtp_circle_background); int backgroundColor = ContextCompat.getColor(context, R.color.mdtp_background_color); int darkBackgroundColor = ContextCompat.getColor(context, R.color.mdtp_light_gray); int lightGray = ContextCompat.getColor(context, R.color.mdtp_light_gray); mTimePicker.setBackgroundColor(mThemeDark ? lightGray : circleBackground); view.findViewById(R.id.time_picker_dialog) .setBackgroundColor(mThemeDark ? darkBackgroundColor : backgroundColor); return view; }
From source file:com.android.mail.browse.MessageHeaderView.java
/** * Render an email list for the expanded message details view. *//* w w w. j a v a2s . c o m*/ private static void renderEmailList(Resources res, int headerId, int detailsId, String[] emails, String viaDomain, View rootView, Map<String, Address> addressCache, Account account, VeiledAddressMatcher veiledMatcher, BidiFormatter bidiFormatter) { if (emails == null || emails.length == 0) { return; } final String[] formattedEmails = new String[emails.length]; for (int i = 0; i < emails.length; i++) { final Address email = Utils.getAddress(addressCache, emails[i]); String name = email.getPersonal(); final String address = email.getAddress(); // Check if the address here is a veiled address. If it is, we need to display an // alternate layout final boolean isVeiledAddress = veiledMatcher != null && veiledMatcher.isVeiledAddress(address); final String addressShown; if (isVeiledAddress) { // Add the warning at the end of the name, and remove the address. The alternate // text cannot be put in the address part, because the address is made into a link, // and the alternate human-readable text is not a link. addressShown = ""; if (TextUtils.isEmpty(name)) { // Empty name and we will block out the address. Let's write something more // readable. name = res.getString(VeiledAddressMatcher.VEILED_ALTERNATE_TEXT_UNKNOWN_PERSON); } else { name = name + res.getString(VeiledAddressMatcher.VEILED_ALTERNATE_TEXT); } } else { addressShown = address; } if (name == null || name.length() == 0 || name.equalsIgnoreCase(addressShown)) { formattedEmails[i] = bidiFormatter.unicodeWrap(addressShown); } else { // The one downside to having the showViaDomain here is that // if the sender does not have a name, it will not show the via info if (viaDomain != null) { formattedEmails[i] = res.getString(R.string.address_display_format_with_via_domain, bidiFormatter.unicodeWrap(name), bidiFormatter.unicodeWrap(addressShown), bidiFormatter.unicodeWrap(viaDomain)); } else { formattedEmails[i] = res.getString(R.string.address_display_format, bidiFormatter.unicodeWrap(name), bidiFormatter.unicodeWrap(addressShown)); } } } rootView.findViewById(headerId).setVisibility(VISIBLE); final TextView detailsText = (TextView) rootView.findViewById(detailsId); detailsText.setText(TextUtils.join("\n", formattedEmails)); stripUnderlines(detailsText, account); detailsText.setVisibility(VISIBLE); }
From source file:com.hichinaschool.flashcards.anki.StudyOptionsActivity.java
/** Handles item selections */ @Override//from w w w . j av a 2 s.c o m public boolean onOptionsItemSelected(MenuItem item) { Resources res = this.getResources(); switch (item.getItemId()) { case android.R.id.home: closeStudyOptions(); return true; case MENU_PREFERENCES: startActivityForResult(new Intent(this, Preferences.class), StudyOptionsFragment.PREFERENCES_UPDATE); if (AnkiDroidApp.SDK_VERSION > 4) { ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.FADE); } return true; case MENU_ROTATE: if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } return true; case MENU_NIGHT: SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this); if (preferences.getBoolean("invertedColors", false)) { preferences.edit().putBoolean("invertedColors", false).commit(); item.setIcon(R.drawable.ic_menu_night); } else { preferences.edit().putBoolean("invertedColors", true).commit(); item.setIcon(R.drawable.ic_menu_night_checked); } return true; case DeckPicker.MENU_CREATE_DYNAMIC_DECK: StyledDialog.Builder builder = new StyledDialog.Builder(StudyOptionsActivity.this); builder.setTitle(res.getString(R.string.new_deck)); mDialogEditText = new EditText(StudyOptionsActivity.this); ArrayList<String> names = AnkiDroidApp.getCol().getDecks().allNames(); int n = 1; String cramDeckName = "Cram 1"; while (names.contains(cramDeckName)) { n++; cramDeckName = "Cram " + n; } mDialogEditText.setText(cramDeckName); // mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter }); builder.setView(mDialogEditText, false, false); builder.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { long id; Bundle initialConfig = new Bundle(); try { initialConfig.putString("searchSuffix", "'deck:" + AnkiDroidApp.getCol().getDecks().current().getString("name") + "'"); id = AnkiDroidApp.getCol().getDecks().newDyn(mDialogEditText.getText().toString()); AnkiDroidApp.getCol().getDecks().get(id); } catch (JSONException e) { throw new RuntimeException(e); } loadContent(false, initialConfig); } }); builder.setNegativeButton(res.getString(R.string.cancel), null); builder.create().show(); return true; default: return super.onOptionsItemSelected(item); } }
From source file:com.ichi2.async.DeckTask.java
private TaskData doInBackgroundImportReplace(TaskData... params) { Timber.d("doInBackgroundImportReplace"); Collection col = CollectionHelper.getInstance().getCol(mContext); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String colPath = col.getPath(); File dir = new File(new File(colPath).getParentFile(), "tmpzip"); if (dir.exists()) { BackupManager.removeDir(dir);//from w w w. j a v a 2 s. c o m } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = new File(dir, "collection.anki2").getAbsolutePath(); ZipFile zip; try { zip = new ZipFile(new File(path), ZipFile.OPEN_READ); } catch (IOException e) { Timber.e(e, "doInBackgroundImportReplace - Error while unzipping"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, dir.getAbsolutePath(), new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } catch (Exception e) { Timber.e("Error opening new collection file... probably it's invalid"); try { tmpCol.close(); } catch (Exception e2) { // do nothing } return new TaskData(-2, null, false); } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); if (col != null) { // unload collection and trigger a backup CollectionHelper.getInstance().closeCollection(true); CollectionHelper.getInstance().lockCollection(); BackupManager.performBackupInBackground(colPath, true); } // overwrite collection File f = new File(colFile); if (!f.renameTo(new File(colPath))) { // Exit early if this didn't work return new TaskData(-2, null, false); } int addedCount = -1; try { col = CollectionHelper.getInstance().reopenCollection(); CollectionHelper.getInstance().unlockCollection(); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(dir.getAbsolutePath(), "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().dir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); return new TaskData(true); } catch (RuntimeException e) { Timber.e(e, "doInBackgroundImportReplace - RuntimeException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Timber.e(e, "doInBackgroundImportReplace - FileNotFoundException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Timber.e(e, "doInBackgroundImportReplace - IOException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }
From source file:com.google.android.marvin.screenspeak.ScreenSpeakService.java
/** * Reloads service preferences./*from w w w .j a v a 2s . c om*/ */ private void reloadPreferences() { final Resources res = getResources(); mAccessibilityEventProcessor.setSpeakCallerId(SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_caller_id_key, R.bool.pref_caller_id_default)); mAccessibilityEventProcessor.setSpeakWhenScreenOff(SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_screenoff_key, R.bool.pref_screenoff_default)); mAutomaticResume = mPrefs.getString(res.getString(R.string.pref_resume_screenspeak_key), getString(R.string.resume_screen_on)); final boolean silenceOnProximity = SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_proximity_key, R.bool.pref_proximity_default); mSpeechController.setSilenceOnProximity(silenceOnProximity); LogUtils.setLogLevel(SharedPreferencesUtils.getIntFromStringPref(mPrefs, res, R.string.pref_log_level_key, R.string.pref_log_level_default)); if (mProcessorFollowFocus != null) { final boolean useSingleTap = SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_single_tap_key, R.bool.pref_single_tap_default); mProcessorFollowFocus.setSingleTapEnabled(useSingleTap); // Update the "X to select" long-hover hint. NodeHintRule.NodeHintHelper.updateActionResId(useSingleTap); } if (mShakeDetector != null) { final int shakeThreshold = SharedPreferencesUtils.getIntFromStringPref(mPrefs, res, R.string.pref_shake_to_read_threshold_key, R.string.pref_shake_to_read_threshold_default); final boolean useShake = (shakeThreshold > 0) && ((mCallStateMonitor == null) || (mCallStateMonitor.getCurrentCallState() == TelephonyManager.CALL_STATE_IDLE)); mShakeDetector.setEnabled(useShake); } if (mSideTapManager != null) { mSideTapManager.onReloadPreferences(); } if (mSupportsTouchScreen) { final boolean touchExploration = SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_explore_by_touch_key, R.bool.pref_explore_by_touch_default); requestTouchExploration(touchExploration); } if (SUPPORTS_WEB_SCRIPT_TOGGLE) { final boolean requestWebScripts = SharedPreferencesUtils.getBooleanPref(mPrefs, res, R.string.pref_web_scripts_key, R.bool.pref_web_scripts_default); requestWebScripts(requestWebScripts); } updateMenuManager(mSpeechController, mFeedbackController); }
From source file:cm.aptoide.com.actionbarsherlock.widget.SearchView.java
/** * Create and return an Intent that can launch the voice search activity, perform a specific * voice transcription, and forward the results to the searchable activity. * * @param baseIntent The voice app search intent to start from * @return A completely-configured intent ready to send to the voice search activity */// ww w.ja va2 s . c o m private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) { ComponentName searchActivity = searchable.getSearchActivity(); // create the necessary intent to set up a search-and-forward operation // in the voice search system. We have to keep the bundle separate, // because it becomes immutable once it enters the PendingIntent Intent queryIntent = new Intent(Intent.ACTION_SEARCH); queryIntent.setComponent(searchActivity); PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT); // Now set up the bundle that will be inserted into the pending intent // when it's time to do the search. We always build it here (even if empty) // because the voice search activity will always need to insert "QUERY" into // it anyway. Bundle queryExtras = new Bundle(); // Now build the intent to launch the voice search. Add all necessary // extras to launch the voice recognizer, and then all the necessary extras // to forward the results to the searchable activity Intent voiceIntent = new Intent(baseIntent); // Add all of the configuration options supplied by the searchable's metadata String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; String prompt = null; String language = null; int maxResults = 1; Resources resources = getResources(); if (searchable.getVoiceLanguageModeId() != 0) { languageModel = resources.getString(searchable.getVoiceLanguageModeId()); } if (searchable.getVoicePromptTextId() != 0) { prompt = resources.getString(searchable.getVoicePromptTextId()); } if (searchable.getVoiceLanguageId() != 0) { language = resources.getString(searchable.getVoiceLanguageId()); } if (searchable.getVoiceMaxResults() != 0) { maxResults = searchable.getVoiceMaxResults(); } voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null : searchActivity.flattenToShortString()); // Add the values that configure forwarding the results voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); return voiceIntent; }
From source file:com.android.launcher3.folder.Folder.java
/** * Used to inflate the Workspace from XML. * * @param context The application's context. * @param attrs The attributes set containing the Workspace's customization values. *//*from w w w .jav a 2 s . c o m*/ public Folder(Context context, AttributeSet attrs) { super(context, attrs); setAlwaysDrawnWithCacheEnabled(false); mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); Resources res = getResources(); mExpandDuration = res.getInteger(R.integer.config_folderExpandDuration); mMaterialExpandDuration = res.getInteger(R.integer.config_materialFolderExpandDuration); mMaterialExpandStagger = res.getInteger(R.integer.config_materialFolderExpandStagger); if (sDefaultFolderName == null) { sDefaultFolderName = res.getString(R.string.folder_name); } if (sHintText == null) { sHintText = res.getString(R.string.folder_hint_text); } mLauncher = Launcher.getLauncher(context); // We need this view to be focusable in touch mode so that when text editing of the folder // name is complete, we have something to focus on, thus hiding the cursor and giving // reliable behavior when clicking the text field (since it will always gain focus on click). setFocusableInTouchMode(true); }
From source file:com.hichinaschool.flashcards.anki.CardEditor.java
@Override protected Dialog onCreateDialog(int id) { StyledDialog dialog = null;/*w w w . j a v a2 s. c o m*/ Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(this); switch (id) { case DIALOG_TAGS_SELECT: builder.setTitle(R.string.card_details_tags); builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mAddNote) { try { JSONArray ja = new JSONArray(); for (String t : selectedTags) { ja.put(t); } mCol.getModels().current().put("tags", ja); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } mEditorNote.setTags(selectedTags); } mCurrentTags = selectedTags; updateTags(); } }); builder.setNegativeButton(res.getString(R.string.cancel), null); mNewTagEditText = (EditText) new EditText(this); mNewTagEditText.setHint(R.string.add_new_tag); InputFilter filter = 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 (source.charAt(i) == ' ' || source.charAt(i) == ',') { return ""; } } return null; } }; mNewTagEditText.setFilters(new InputFilter[] { filter }); ImageView mAddTextButton = new ImageView(this); mAddTextButton.setImageResource(R.drawable.ic_addtag); mAddTextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tag = mNewTagEditText.getText().toString(); if (tag.length() != 0) { if (mEditorNote.hasTag(tag)) { mNewTagEditText.setText(""); return; } selectedTags.add(tag); actualizeTagDialog(mTagsDialog); mNewTagEditText.setText(""); } } }); FrameLayout frame = new FrameLayout(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL); params.rightMargin = 10; mAddTextButton.setLayoutParams(params); frame.addView(mNewTagEditText); frame.addView(mAddTextButton); builder.setView(frame, false, true); dialog = builder.create(); mTagsDialog = dialog; break; case DIALOG_DECK_SELECT: ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogDeckIds = new ArrayList<Long>(); ArrayList<JSONObject> decks = mCol.getDecks().all(); Collections.sort(decks, new JSONNameComparator()); builder.setTitle(R.string.deck); for (JSONObject d : decks) { try { if (d.getInt("dyn") == 0) { dialogDeckItems.add(d.getString("name")); dialogDeckIds.add(d.getLong("id")); } } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items = new String[dialogDeckItems.size()]; dialogDeckItems.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long newId = dialogDeckIds.get(item); if (mCurrentDid != newId) { if (mAddNote) { try { // TODO: mEditorNote.setDid(newId); mEditorNote.model().put("did", newId); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } } mCurrentDid = newId; updateDeck(); } } }); dialog = builder.create(); mDeckSelectDialog = dialog; break; case DIALOG_MODEL_SELECT: ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogIds = new ArrayList<Long>(); ArrayList<JSONObject> models = mCol.getModels().all(); Collections.sort(models, new JSONNameComparator()); builder.setTitle(R.string.note_type); for (JSONObject m : models) { try { dialogItems.add(m.getString("name")); dialogIds.add(m.getLong("id")); } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items2 = new String[dialogItems.size()]; dialogItems.toArray(items2); builder.setItems(items2, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long oldModelId; try { oldModelId = mCol.getModels().current().getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } long newId = dialogIds.get(item); if (oldModelId != newId) { mCol.getModels().setCurrent(mCol.getModels().get(newId)); JSONObject cdeck = mCol.getDecks().current(); try { cdeck.put("mid", newId); } catch (JSONException e) { throw new RuntimeException(e); } mCol.getDecks().save(cdeck); int size = mEditFields.size(); String[] oldValues = new String[size]; for (int i = 0; i < size; i++) { oldValues[i] = mEditFields.get(i).getText().toString(); } setNote(); resetEditFields(oldValues); mTimerHandler.removeCallbacks(checkDuplicatesRunnable); duplicateCheck(false); } } }); dialog = builder.create(); break; case DIALOG_RESET_CARD: builder.setTitle(res.getString(R.string.reset_card_dialog_title)); builder.setMessage(res.getString(R.string.reset_card_dialog_message)); builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // for (long cardId : // mDeck.getCardsFromFactId(mEditorNote.getId())) { // mDeck.cardFromId(cardId).resetCard(); // } // mDeck.reset(); // setResult(Reviewer.RESULT_EDIT_CARD_RESET); // mCardReset = true; // Themes.showThemedToast(CardEditor.this, // getResources().getString( // R.string.reset_card_dialog_confirmation), true); } }); builder.setNegativeButton(res.getString(R.string.no), null); builder.setCancelable(true); dialog = builder.create(); break; case DIALOG_INTENT_INFORMATION: dialog = createDialogIntentInformation(builder, res); } return dialog; }