List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder
public SpannableStringBuilder()
From source file:com.kyakujin.android.autoeco.ui.MainActivity.java
/** * About//from w w w.jav a 2 s . c o m */ private void showAboutDialog() { PackageManager pm = this.getPackageManager(); String packageName = this.getPackageName(); String versionName; try { PackageInfo info = pm.getPackageInfo(packageName, 0); versionName = info.versionName; } catch (PackageManager.NameNotFoundException e) { versionName = "N/A"; } SpannableStringBuilder aboutBody = new SpannableStringBuilder(); SpannableString mailAddress = new SpannableString(getString(R.string.mailto)); mailAddress.setSpan(new ClickableSpan() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SENDTO); intent.setData(Uri.parse(getString(R.string.description_mailto))); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject)); startActivity(intent); } }, 0, mailAddress.length(), 0); aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName))); aboutBody.append("\n"); aboutBody.append(mailAddress); LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null); aboutBodyView.setText(aboutBody); aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance()); AlertDialog dlg = new AlertDialog.Builder(this).setTitle(R.string.alert_title_about).setView(aboutBodyView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dlg.show(); }
From source file:com.todoroo.astrid.adapter.TaskAdapter.java
private void setupDueDateAndTags(ViewHolder viewHolder, Task task) { // due date / completion date final TextView dueDateView = viewHolder.dueDate; {//w w w . j a v a 2 s. com if (!task.isCompleted() && task.hasDueDate()) { long dueDate = task.getDueDate(); if (task.isOverdue()) { dueDateView.setTextColor(textColorOverdue); } else { dueDateView.setTextColor(textColorSecondary); } String dateValue = DateUtilities.getRelativeDateStringWithTime(context, dueDate); dueDateView.setText(dateValue); dueDateView.setVisibility(View.VISIBLE); } else if (task.isCompleted()) { String dateValue = DateUtilities.getRelativeDateStringWithTime(context, task.getCompletionDate()); dueDateView.setText(resources.getString(R.string.TAd_completed, dateValue)); dueDateView.setTextColor(textColorHint); dueDateView.setVisibility(View.VISIBLE); } else { dueDateView.setVisibility(View.GONE); } if (task.isCompleted()) { viewHolder.tagBlock.setVisibility(View.GONE); } else { String tags = viewHolder.tagsString; List<String> tagUuids = tags != null ? newArrayList(tags.split(",")) : Lists.newArrayList(); Iterable<TagData> t = filter(transform(tagUuids, uuidToTag), Predicates.notNull()); List<TagData> firstFourByName = orderByName.leastOf(t, 4); int numTags = firstFourByName.size(); if (numTags > 0) { List<TagData> firstFourByNameLength = orderByLength.sortedCopy(firstFourByName); float maxLength = tagCharacters / numTags; for (int i = 0; i < numTags - 1; i++) { TagData tagData = firstFourByNameLength.get(i); String name = tagData.getName(); if (name.length() >= maxLength) { break; } float excess = maxLength - name.length(); int beneficiaries = numTags - i - 1; float additional = excess / beneficiaries; maxLength += additional; } List<SpannableString> tagStrings = transform(firstFourByName, tagToString(maxLength)); SpannableStringBuilder builder = new SpannableStringBuilder(); for (SpannableString tagString : tagStrings) { if (builder.length() > 0) { builder.append(HAIR_SPACE); } builder.append(tagString); } viewHolder.tagBlock.setText(builder); viewHolder.tagBlock.setVisibility(View.VISIBLE); } else { viewHolder.tagBlock.setVisibility(View.GONE); } } } }
From source file:com.juick.android.JuickMessagesAdapter.java
public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) { if (jmsg.parsedText != null) { return (ParsedMessage) jmsg.parsedText; // was parsed before }/* w ww . j a va2 s . c o m*/ getColorTheme(ctx); SpannableStringBuilder ssb = new SpannableStringBuilder(); int spanOffset = 0; final boolean isMainMessage = jmsg.getRID() == 0; final boolean doCompactComment = !isMainMessage && compactComments; if (jmsg.continuationInformation != null) { ssb.append(jmsg.continuationInformation + "\n"); ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // // NAME // spanOffset = ssb.length(); String name = '@' + jmsg.User.UName; int userNameStart = ssb.length(); ssb.append(name); int userNameEnd = ssb.length(); StyleSpan userNameBoldSpan; ForegroundColorSpan userNameColorSpan; ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan( userNameColorSpan = new ForegroundColorSpan( colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (helvNueFonts) { ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } ssb.append(' '); spanOffset = ssb.length(); if (!condensed) { // // TAGS // String tags = jmsg.getTags(); if (feedlyFonts) tags = tags.toUpperCase(); ssb.append(tags + "\n"); if (tags.length() > 0) { ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (feedlyFonts) { ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (helvNueFonts) { ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } spanOffset = ssb.length(); } if (jmsg.translated) { // // 'translated' // ssb.append("translated: "); ssb.setSpan( new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spanOffset = ssb.length(); } int bodyOffset = ssb.length(); int messageNumberStart = -1, messageNumberEnd = -1; if (showNumbers(ctx) && !condensed) { // // numbers // if (isMainMessage) { messageNumberStart = ssb.length(); ssb.append(jmsg.getDisplayMessageNo()); messageNumberEnd = ssb.length(); } else { ssb.append("/" + jmsg.getRID()); if (jmsg.getReplyTo() != 0) { ssb.append("->" + jmsg.getReplyTo()); } } ssb.append(" "); ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spanOffset = ssb.length(); } // // MESSAGE BODY // String txt = Censor.getCensoredText(jmsg.Text); if (!condensed) { if (jmsg.Photo != null) { txt = jmsg.Photo + "\n" + txt; } if (jmsg.Video != null) { txt = jmsg.Video + "\n" + txt; } } ssb.append(txt); boolean ssbChanged = false; // allocation optimization // Highlight links http://example.com/ ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID()); ArrayList<String> urls = new ArrayList<String>(); for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) { setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)), spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); urls.add(foundURL.url); if (foundURL.title != null) { ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " "); ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " "); ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "("); ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")"); ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start, spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } ssbChanged = true; } // bold italic underline if (jmsg.Text.indexOf("*") != -1) { setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*"); ssbChanged = true; } if (jmsg.Text.indexOf("/") != 0) { setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/"); ssbChanged = true; } if (jmsg.Text.indexOf("_") != 0) { setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_"); ssbChanged = true; } if (ssbChanged) { txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between } // Highlight nick String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx); if (accountName != null) { int scan = spanOffset; String nickScanArea = (ssb + " ").toUpperCase(); while (true) { int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan); if (myNick != -1) { if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) { setSSBSpan(ssb, new BackgroundColorSpan( colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)), myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } scan = myNick + 1; } else { break; } } } // Highlight messages #1234 int pos = 0; Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt); while (m.find(pos)) { ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)), spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); pos = m.end(); } SpannableStringBuilder compactDt = null; if (!condensed) { // found messages count (search results) if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) { ssb.append("\n"); int where = ssb.length(); if (jmsg.myFoundCount != 0) { ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + " "); } if (jmsg.hisFoundCount != 0) { ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount); } ssb.setSpan( new ForegroundColorSpan( colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)), where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } int rightPartOffset = spanOffset = ssb.length(); if (!doCompactComment) { // // TIME (bottom of message) // try { DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy"); String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]"; if (date.endsWith("/76")) date = date.substring(0, date.length() - 3); // special case for no year in datasource ssb.append("\n" + date + " "); } catch (Exception e) { ssb.append("\n[fmt err] "); } ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { compactDt = new SpannableStringBuilder(); try { if (true || jmsg.deltaTime != Long.MIN_VALUE) { compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian)); } else { DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy"); String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]"; if (date.endsWith("/76")) date = date.substring(0, date.length() - 3); // special case for no year in datasource compactDt.append(date); } } catch (Exception e) { compactDt.append("\n[fmt err] "); } compactDt.setSpan( new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0, compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } spanOffset = ssb.length(); // // Number of REPLIES // if (jmsg.replies > 0) { String replies = Replies + jmsg.replies; ssb.append(" " + replies); ssb.setSpan( new ForegroundColorSpan( colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)), spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new WrapTogetherSpan() { }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if (!doCompactComment) { // right align ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } if (helvNueFonts) { ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null; if (showUserpics(ctx) && !condensed) { userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() { @Override public int getLeadingMarginLineCount() { if (_wrapUserpics) { return 2; } else { return 22222; } } @Override public int getLeadingMargin(boolean first) { if (first) { return (int) (2 * getLineHeight(ctx, (double) textScale)); } else { return 0; } } @Override public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { } }; ssb.setSpan(userpicSpan, 0, ssb.length(), 0); } ParsedMessage parsedMessage = new ParsedMessage(ssb, urls); parsedMessage.userpicSpan = userpicSpan; parsedMessage.userNameBoldSpan = userNameBoldSpan; parsedMessage.userNameColorSpan = userNameColorSpan; parsedMessage.userNameStart = userNameStart; parsedMessage.userNameEnd = userNameEnd; parsedMessage.messageNumberStart = messageNumberStart; parsedMessage.messageNumberEnd = messageNumberEnd; parsedMessage.compactDate = compactDt; return parsedMessage; }
From source file:com.android.launcher3.Launcher.java
@Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(// ww w . ja v a 2s .c o m new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { if (LauncherAppState.PROFILE_STARTUP) { Trace.beginSection("Launcher-onCreate"); } } predictiveAppsProvider = new PredictiveAppsProvider(this); if (mLauncherCallbacks != null) { mLauncherCallbacks.preOnCreate(); } super.onCreate(savedInstanceState); app = LauncherAppState.getInstance(); // Load configuration-specific DeviceProfile mDeviceProfile = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? app.getInvariantDeviceProfile().landscapeProfile : app.getInvariantDeviceProfile().portraitProfile; mSharedPrefs = Utilities.getPrefs(this); mIsSafeModeEnabled = getPackageManager().isSafeMode(); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mAccessibilityDelegate = new LauncherAccessibilityDelegate(this); mDragController = new DragController(this); mAllAppsController = new AllAppsTransitionController(this); mStateTransitionAnimation = new LauncherStateTransitionAnimation(this, mAllAppsController); mAppWidgetManager = AppWidgetManagerCompat.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; setContentView(R.layout.launcher); //Shortcuts variable init masterLayout = (InsettableFrameLayout) findViewById(R.id.launcher); gridSize = new GridSize((int) app.getInvariantDeviceProfile().numColumns, (int) app.getInvariantDeviceProfile().numRows); IS_ALLOW_MIC = Utilities.isAllowVoiceInSearchBarPrefEnabled(getApplicationContext()); setupViews(); mDeviceProfile.layout(this, false /* notifyListeners */); mExtractedColors = new ExtractedColors(); loadExtractedColorsAndColorItems(); ((AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE)).addAccessibilityStateChangeListener(this); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); if (LauncherAppState.PROFILE_STARTUP) { Trace.endSection(); } // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground if (!mModel.startLoader(mWorkspace.getRestorePage())) { // If we are not binding synchronously, show a fade in animation when // the first page bind completes. mDragLayer.setAlpha(0); } else { setWorkspaceLoading(true); } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(ACTION_APPWIDGET_HOST_RESET); registerReceiver(mUiBroadcastReceiver, filter); mRotationEnabled = getResources().getBoolean(R.bool.allow_rotation); // In case we are on a device with locked rotation, we should look at preferences to check // if the user has specifically allowed rotation. if (!mRotationEnabled) { mRotationEnabled = Utilities.isAllowRotationPrefEnabled(getApplicationContext()); mRotationPrefChangeHandler = new RotationPrefChangeHandler(); mSharedPrefs.registerOnSharedPreferenceChangeListener(mRotationPrefChangeHandler); } // On large interfaces, or on devices that a user has specifically enabled screen rotation, // we want the screen to auto-rotate based on the current orientation setOrientation(); if (mLauncherCallbacks != null) { mLauncherCallbacks.onCreate(savedInstanceState); } activity = this; /*if (!isTaskRoot()) { finish(); return; }*/ adminComponent = new ComponentName(Launcher.this, DarClass.class); devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); appHasFingerprint = Utilities.getAppHasFingerprint(getApplicationContext()); appHasPassword = Utilities.getAppHasPassword(getApplicationContext()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); } icons = Utilities.getIconPack(Utilities.getAppIconPackageNamePrefEnabled(getApplicationContext())); if (icons == null || icons.isEmpty() || icons.size() == 0) { if (Utilities.getAppIconPackageNamePrefEnabled(getApplicationContext()) != null && !Utilities .getAppIconPackageNamePrefEnabled(getApplicationContext()).equalsIgnoreCase("NULL")) { Utilities.answerToRestoreIconPack(this, Utilities.getAppIconPackageNamePrefEnabled(getApplicationContext())); } } if (FirstRun.isFirstLaunch(getApplicationContext())) { WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext()); try { myWallpaperManager.setResource(R.drawable.wallpaper); } catch (IOException e) { e.printStackTrace(); } } if (Utilities.doCheckPROVersion(getApplicationContext())) { } mDefaultScreenId = Utilities.getLongCustomDefault(this, Utilities.SETTINGS_UI_HOMESCREEN_DEFAULT_SCREEN_ID, 1); }
From source file:com.klinker.android.launcher.launcher3.Launcher.java
@Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(/*from w ww. ja v a2s.c o m*/ new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); } predictiveAppsProvider = new PredictiveAppsProvider(this); if (mLauncherCallbacks != null) { mLauncherCallbacks.preOnCreate(); } try { super.onCreate(savedInstanceState); } catch (Exception e) { super.onCreate(new Bundle()); } LauncherAppState.setApplicationContext(getApplicationContext()); LauncherAppState app = LauncherAppState.getInstance(); // Load configuration-specific DeviceProfile mDeviceProfile = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? app.getInvariantDeviceProfile().landscapeProfile : app.getInvariantDeviceProfile().portraitProfile; mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE); mIsSafeModeEnabled = getPackageManager().isSafeMode(); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mDragController = new DragController(this); mInflater = getLayoutInflater(); mStateTransitionAnimation = new LauncherStateTransitionAnimation(this, this); mStats = new Stats(this); mAppWidgetManager = AppWidgetManagerCompat.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing(Environment.getExternalStorageDirectory() + "/launcher"); } setContentView(R.layout.launcher); setupViews(); setUpBlur(); mDeviceProfile.layout(this); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) { // If the user leaves launcher, then we should just load items asynchronously when // they return. mModel.startLoader(PagedView.INVALID_RESTORE_PAGE); } else { // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground mModel.startLoader(mWorkspace.getRestorePage()); } } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); mRotationEnabled = Utilities.isRotationAllowedForDevice(getApplicationContext()); // In case we are on a device with locked rotation, we should look at preferences to check // if the user has specifically allowed rotation. if (!mRotationEnabled) { mRotationEnabled = Utilities.isAllowRotationPrefEnabled(getApplicationContext(), false); } // On large interfaces, or on devices that a user has specifically enabled screen rotation, // we want the screen to auto-rotate based on the current orientation setOrientation(); if (mLauncherCallbacks != null) { mLauncherCallbacks.onCreate(savedInstanceState); if (mLauncherCallbacks.hasLauncherOverlay()) { ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub); mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate(); mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(mLauncherOverlayContainer, mLauncherOverlayCallbacks); mWorkspace.setLauncherOverlay(mLauncherOverlay); } } if (shouldShowIntroScreen()) { showIntroScreen(); } else { showFirstRunActivity(); showFirstRunClings(); } }
From source file:g7.bluesky.launcher3.Launcher.java
@Override protected void onCreate(Bundle savedInstanceState) { activity = this; if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(/*from ww w . j a va 2s. co m*/ new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); } if (mLauncherCallbacks != null) { mLauncherCallbacks.preOnCreate(); } super.onCreate(savedInstanceState); LauncherAppState.setApplicationContext(getApplicationContext()); LauncherAppState app = LauncherAppState.getInstance(); LauncherAppState.getLauncherProvider().setLauncherProviderChangeListener(this); // Lazy-initialize the dynamic grid DeviceProfile grid = app.initDynamicGrid(this); // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE); // Set defaultSharedPref defaultSharedPref = PreferenceManager.getDefaultSharedPreferences(this); mIsSafeModeEnabled = getPackageManager().isSafeMode(); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mIconCache.flushInvalidIcons(grid); mDragController = new DragController(this); mInflater = getLayoutInflater(); mStats = new Stats(this); mAppWidgetManager = AppWidgetManagerCompat.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing(Environment.getExternalStorageDirectory() + "/launcher"); } checkForLocaleChange(); setContentView(R.layout.launcher); setupViews(); grid.layout(this); registerContentObservers(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) { // If the user leaves launcher, then we should just load items asynchronously when // they return. mModel.startLoader(true, PagedView.INVALID_RESTORE_PAGE); } else { // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground mModel.startLoader(true, mWorkspace.getRestorePage()); } } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); // On large interfaces, we want the screen to auto-rotate based on the current orientation unlockScreenOrientation(true); if (mLauncherCallbacks != null) { mLauncherCallbacks.onCreate(savedInstanceState); if (mLauncherCallbacks.hasLauncherOverlay()) { ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub); mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate(); mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(mLauncherOverlayContainer, mLauncherOverlayCallbacks); mWorkspace.setLauncherOverlay(mLauncherOverlay); } } if (shouldShowIntroScreen()) { showIntroScreen(); } else { showFirstRunActivity(); showFirstRunClings(); } //create extramenu //llExtraMenu = (LinearLayout) findViewById(R.id.ll_extra_menu); //llExtraMenu.addView(new ExtraMenu(this, null)); flLauncher = (LauncherRootView) findViewById(R.id.launcher); mExtraMenu = new ExtraMenu(this, null); flLauncher.addView(mExtraMenu); if (!defaultSharedPref.getBoolean(SettingConstants.EXTRA_MENU_PREF_KEY, false)) { mExtraMenu.setVisibility(View.GONE); } editTextFilterApps.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { String searchString = editTextFilterApps.getText().toString(); if (listApps != null && listApps.size() > 0) { if (searchString.trim().length() > 0) { ArrayList<AppInfo> searchList = new ArrayList<>(); for (AppInfo appInfo : listApps) { String appTitle = StringUtil .convertVNString(appInfo.getTitle().toString().toLowerCase().trim()); searchString = StringUtil.convertVNString(searchString.toLowerCase().trim()); if (appTitle.contains(searchString)) { searchList.add(appInfo); } } mAppsCustomizeContent.setApps(searchList); } else { mAppsCustomizeContent.setApps((ArrayList<AppInfo>) listApps); } } } }); // Spinner element Spinner spinner = (Spinner) findViewById(R.id.spinner); // Spinner click listener spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Clear spinner text ((TextView) view).setText(null); SharedPreferences.Editor editor = defaultSharedPref.edit(); editor.putInt(SettingConstants.SORT_PREF_KEY, position); editor.apply(); // Value from preference int prefVal = defaultSharedPref.getInt(SettingConstants.SORT_PREF_KEY, SettingConstants.SORT_A_Z); LauncherUtil.sortListApps(defaultSharedPref, listApps, prefVal); mAppsCustomizeContent.invalidatePageData(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); // Creating adapter for spinner ArrayAdapter<CharSequence> dataAdapter = ArrayAdapter.createFromResource(this, R.array.sort_options, android.R.layout.simple_spinner_item); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); // attaching data adapter to spinner spinner.setAdapter(dataAdapter); // Set default value final int prefSortOptionVal = defaultSharedPref.getInt(SettingConstants.SORT_PREF_KEY, SettingConstants.SORT_A_Z); spinner.setSelection(prefSortOptionVal); // Listen on pref change prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equalsIgnoreCase(SettingConstants.EXTRA_MENU_PREF_KEY)) { if (!defaultSharedPref.getBoolean(SettingConstants.EXTRA_MENU_PREF_KEY, false)) { mExtraMenu.setVisibility(View.GONE); } else { mExtraMenu.setVisibility(View.VISIBLE); } } else if (key.equalsIgnoreCase(SettingConstants.ICON_THEME_PREF_KEY)) { mModel.forceReload(); loadIconPack(); } } }; defaultSharedPref.registerOnSharedPreferenceChangeListener(prefChangeListener); }
From source file:com.android.soma.Launcher.java
@Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(/*from w w w . j av a2s .c om*/ new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); } super.onCreate(savedInstanceState); LauncherAppState.setApplicationContext(getApplicationContext()); LauncherAppState app = LauncherAppState.getInstance(); // Determine the dynamic grid properties Point smallestSize = new Point(); Point largestSize = new Point(); Point realSize = new Point(); Display display = getWindowManager().getDefaultDisplay(); display.getCurrentSizeRange(smallestSize, largestSize); display.getRealSize(realSize); DisplayMetrics dm = new DisplayMetrics(); display.getMetrics(dm); // Lazy-initialize the dynamic grid DeviceProfile grid = app.initDynamicGrid(this, Math.min(smallestSize.x, smallestSize.y), Math.min(largestSize.x, largestSize.y), realSize.x, realSize.y, dm.widthPixels, dm.heightPixels); // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mIconCache.flushInvalidIcons(grid); mDragController = new DragController(this); mInflater = getLayoutInflater(); mStats = new Stats(this); mAppWidgetManager = AppWidgetManager.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing(Environment.getExternalStorageDirectory() + "/launcher"); } checkForLocaleChange(); setContentView(R.layout.launcher); setupViews(); grid.layout(this); registerContentObservers(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); // Update customization drawer _after_ restoring the states if (mAppsCustomizeContent != null) { mAppsCustomizeContent.onPackagesUpdated(LauncherModel.getSortedWidgetsAndShortcuts(this)); } { { final RajawaliSurfaceView surface = new RajawaliSurfaceView(this); surface.setFrameRate(60.0); surface.setRenderMode(IRajawaliSurface.RENDERMODE_WHEN_DIRTY); // Add mSurface to your root view addContentView(surface, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT)); mRenderer = new WallpaperRenderer(this); surface.setSurfaceRenderer(mRenderer); } } if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { if (sPausedFromUserAction) { // If the user leaves launcher, then we should just load items asynchronously when // they return. mModel.startLoader(true, -1); } else { // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground mModel.startLoader(true, mWorkspace.getCurrentPage()); } } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); updateGlobalIcons(); // On large interfaces, we want the screen to auto-rotate based on the current orientation unlockScreenOrientation(true); showFirstRunCling(); // following code is for Native method support test { } }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
private CharSequence formatMessage(String contact, String body, String contentType) { System.out.println("MessageAdapter.java in formatMessage() "); SpannableStringBuilder buf = new SpannableStringBuilder(); if (!TextUtils.isEmpty(body)) { // Converts html to spannable if ContentType is "text/html". if (contentType != null && "text/html".equals(contentType)) { buf.append("\n"); buf.append(Html.fromHtml(body)); } else {/*from w ww.j a v a 2s . co m*/ SmileyParser parser = SmileyParser.getInstance(); buf.append(parser.addSmileySpans(body)); } } // We always show two lines because the optional icon bottoms are // aligned with the // bottom of the text field, assuming there are two lines for the // message and the sent time. buf.append("\n"); int startOffset = buf.length(); startOffset = buf.length(); buf.setSpan(mTextSmallSpan, startOffset, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); System.out.println("formatMessage:" + buf); return buf; }
From source file:com.mattprecious.notisync.service.SecondaryService.java
/** * Taken and modified from AOSP MMS app. * src/com/android/mms/transaction/MessagingNotification.java *//*from ww w .j a v a 2s. co m*/ private Notification buildRichNotification(NotificationCompat.Builder builder, List<List<NotificationData>> threadList, Bitmap photoIfSingleThread) { if (threadList.size() == 0) { return builder.build(); } final TextAppearanceSpan primarySpan = new TextAppearanceSpan(this, R.style.NotificationPrimaryText); final TextAppearanceSpan secondarySpan = new TextAppearanceSpan(this, R.style.NotificationSecondaryText); // only one thread if (threadList.size() == 1) { List<NotificationData> thread = threadList.get(0); NotificationData lastData = thread.get(thread.size() - 1); builder.setContentTitle(lastData.sender); if (photoIfSingleThread != null) { builder.setLargeIcon(resizePhoto(photoIfSingleThread)); } // only one message, display the whole thing if (thread.size() == 1) { String message = dedupeNewlines(lastData.message); builder.setContentText(message); return new NotificationCompat.BigTextStyle(builder).bigText(message) // Forcibly show the last line, with the smallIcon in // it, if we kicked the smallIcon out with a photo // bitmap .setSummaryText((photoIfSingleThread == null) ? null : " ").build(); } else { // multiple messages for the same thread SpannableStringBuilder buf = new SpannableStringBuilder(); boolean first = true; for (NotificationData data : thread) { // remove extra newlines String message = dedupeNewlines(data.message); if (first) { first = false; } else { buf.append('\n'); } buf.append(message); } builder.setContentTitle(getString(R.string.noti_title_new_messages, thread.size())); return new NotificationCompat.BigTextStyle(builder).bigText(buf) // Forcibly show the last line, with the smallIcon in // it, if we kicked the smallIcon out with a photo // bitmap .setSummaryText((photoIfSingleThread == null) ? null : " ").build(); } } else { // multiple threads String separator = ", "; SpannableStringBuilder contentStringBuilder = new SpannableStringBuilder(); boolean first = true; int totalMessageCount = 0; for (List<NotificationData> thread : threadList) { totalMessageCount += thread.size(); if (first) { first = false; } else { contentStringBuilder.append(separator); } NotificationData lastData = thread.get(thread.size() - 1); contentStringBuilder.append(lastData.sender); } builder.setContentTitle(getString(R.string.noti_title_new_messages, totalMessageCount)); builder.setContentText(contentStringBuilder); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder); // We have to set the summary text to non-empty so the content text // doesn't show up when expanded. inboxStyle.setSummaryText(" "); int c = 0; for (List<NotificationData> dataList : threadList) { if (c == 8) break; NotificationData lastData = dataList.get(dataList.size() - 1); SpannableStringBuilder inboxStringBuilder = new SpannableStringBuilder(); int senderLength = lastData.sender.length(); inboxStringBuilder.append(lastData.sender).append(": "); inboxStringBuilder.setSpan(primarySpan, 0, senderLength, 0); inboxStringBuilder.append(dedupeNewlines(lastData.message)); inboxStringBuilder.setSpan(secondarySpan, senderLength, senderLength + lastData.sender.length(), 0); inboxStyle.addLine(inboxStringBuilder); } return inboxStyle.build(); } }
From source file:org.miaowo.miaowo.util.Html.java
public HtmlToSpannedConverter(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler, Parser parser, int flags, Context context) { mSource = source;//from w ww.ja v a 2s . co m mSpannableStringBuilder = new SpannableStringBuilder(); mImageGetter = imageGetter; mTagHandler = tagHandler; mReader = parser; mFlags = flags; mContext = context; }