List of usage examples for android.text SpannableString length
int length();
From source file:com.android.messaging.datamodel.MessageNotificationState.java
public static Notification buildConversationPageForWearable(final String conversationId, int participantCount) { final Context context = Factory.get().getApplicationContext(); // Limit the number of messages to show. We just want enough to provide context for the // notification. Fetch one more than we need, so we can tell if there are more messages // before the one we're showing. // TODO: in the query, a multipart message will contain a row for each part. // We might need a smarter GROUP_BY. On the other hand, we might want to show each of the // parts as separate messages on the wearable. final int limit = MAX_MESSAGES_IN_WEARABLE_PAGE + 1; final List<CharSequence> messages = Lists.newArrayList(); boolean hasSeenMessagesBeforeNotification = false; Cursor convMessageCursor = null; try {//from w ww.ja va 2 s . c om final DatabaseWrapper db = DataModel.get().getDatabase(); final String[] queryArgs = { conversationId }; final String convPageSql = ConversationMessageData.getWearableQuerySql() + " LIMIT " + limit; convMessageCursor = db.rawQuery(convPageSql, queryArgs); if (convMessageCursor == null || !convMessageCursor.moveToFirst()) { return null; } final ConversationMessageData convMessageData = new ConversationMessageData(); final HashMap<String, Integer> firstNames = scanFirstNames(conversationId); do { convMessageData.bind(convMessageCursor); final String authorFullName = convMessageData.getSenderFullName(); final String authorFirstName = convMessageData.getSenderFirstName(); String text = convMessageData.getText(); final boolean isSmsPushNotification = convMessageData.getIsMmsNotification(); // if auto-download was off to show a message to tap to download the message. We // might need to get that working again. if (isSmsPushNotification && text != null) { text = convertHtmlAndStripUrls(text).toString(); } // Skip messages without any content if (TextUtils.isEmpty(text) && !convMessageData.hasAttachments()) { continue; } // Track whether there are messages prior to the one(s) shown in the notification. if (convMessageData.getIsSeen()) { hasSeenMessagesBeforeNotification = true; } final boolean usedMoreThanOnce = firstNameUsedMoreThanOnce(firstNames, authorFirstName); String displayName = usedMoreThanOnce ? authorFullName : authorFirstName; if (TextUtils.isEmpty(displayName)) { if (convMessageData.getIsIncoming()) { displayName = convMessageData.getSenderDisplayDestination(); if (TextUtils.isEmpty(displayName)) { displayName = context.getString(R.string.unknown_sender); } } else { displayName = context.getString(R.string.unknown_self_participant); } } Uri attachmentUri = null; String attachmentType = null; final List<MessagePartData> attachments = convMessageData.getAttachments(); for (final MessagePartData messagePartData : attachments) { // Look for the first attachment that's not the text piece. if (!messagePartData.isText()) { attachmentUri = messagePartData.getContentUri(); attachmentType = messagePartData.getContentType(); break; } } final CharSequence message = BugleNotifications.buildSpaceSeparatedMessage(displayName, text, attachmentUri, attachmentType); messages.add(message); } while (convMessageCursor.moveToNext()); } finally { if (convMessageCursor != null) { convMessageCursor.close(); } } // If there is no conversation history prior to what is already visible in the main // notification, there's no need to include the conversation log, too. final int maxMessagesInNotification = getMaxMessagesInConversationNotification(); if (!hasSeenMessagesBeforeNotification && messages.size() <= maxMessagesInNotification) { return null; } final SpannableStringBuilder bigText = new SpannableStringBuilder(); // There is at least 1 message prior to the first one that we're going to show. // Indicate this by inserting an ellipsis at the beginning of the conversation log. if (convMessageCursor.getCount() == limit) { bigText.append(context.getString(R.string.ellipsis) + "\n\n"); if (messages.size() > MAX_MESSAGES_IN_WEARABLE_PAGE) { messages.remove(messages.size() - 1); } } // Messages are sorted in descending timestamp order, so iterate backwards // to get them back in ascending order for display purposes. for (int i = messages.size() - 1; i >= 0; --i) { bigText.append(messages.get(i)); if (i > 0) { bigText.append("\n\n"); } } ++participantCount; // Add in myself if (participantCount > 2) { final SpannableString statusText = new SpannableString(context.getResources() .getQuantityString(R.plurals.wearable_participant_count, participantCount, participantCount)); statusText.setSpan( new ForegroundColorSpan( context.getResources().getColor(R.color.wearable_notification_participants_count)), 0, statusText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); bigText.append("\n\n").append(statusText); } final NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context); final NotificationCompat.Style notifStyle = new NotificationCompat.BigTextStyle(notifBuilder) .bigText(bigText); notifBuilder.setStyle(notifStyle); final WearableExtender wearableExtender = new WearableExtender(); wearableExtender.setStartScrollBottom(true); notifBuilder.extend(wearableExtender); return notifBuilder.build(); }
From source file:io.github.hidroh.materialistic.data.HackerNewsItem.java
@Override public Spannable getDisplayedTime(Context context) { if (displayedTime == null) { SpannableStringBuilder builder = new SpannableStringBuilder( dead ? context.getString(R.string.dead_prefix) + " " : ""); SpannableString timeSpannable = new SpannableString(AppUtils.getAbbreviatedTimeSpan(time * 1000)); if (deleted) { timeSpannable.setSpan(new StrikethroughSpan(), 0, timeSpannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); }/*from w ww . ja va 2s. co m*/ builder.append(timeSpannable); displayedTime = builder; } return displayedTime; }
From source file:uk.co.ashtonbrsc.intentexplode.Explode.java
private void addTextToLayout(String text, int typeface, int paddingLeft, LinearLayout layout) { TextView textView = new TextView(this); ParagraphStyle style_para = new LeadingMarginSpan.Standard(0, (int) (STANDARD_INDENT_SIZE_IN_DIP * density)); SpannableString styledText = new SpannableString(text); styledText.setSpan(style_para, 0, styledText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); textView.setText(styledText);/*from w w w . j av a 2 s .c om*/ textView.setTextAppearance(this, R.style.TextFlags); textView.setTypeface(null, typeface); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); params.setMargins((int) (paddingLeft * density), 0, 0, 0); layout.addView(textView, params); }
From source file:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java
@Override public Dialog onCreateDialog(final Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); final FragmentActivity activity = getActivity(); final LayoutInflater inflater = LayoutInflater.from(activity); final Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_Dialog)) .setTitle(R.string.transaction_summary_title); final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.transaction_summary_fragment, null); dialog.setView(view);/*from w ww .j ava2 s . co m*/ try { final MyRemoteWallet wallet = application.getRemoteWallet(); BigInteger totalOutputValue = BigInteger.ZERO; for (TransactionOutput output : tx.getOutputs()) { totalOutputValue = totalOutputValue.add(output.getValue()); } final TextView resultDescriptionView = (TextView) view.findViewById(R.id.result_description); final TextView toView = (TextView) view.findViewById(R.id.transaction_to); final TextView toViewLabel = (TextView) view.findViewById(R.id.transaction_to_label); final View toViewContainer = (View) view.findViewById(R.id.transaction_to_container); final TextView hashView = (TextView) view.findViewById(R.id.transaction_hash); final TextView transactionTimeView = (TextView) view.findViewById(R.id.transaction_date); final TextView confirmationsView = (TextView) view.findViewById(R.id.transaction_confirmations); final TextView noteView = (TextView) view.findViewById(R.id.transaction_note); final Button addNoteButton = (Button) view.findViewById(R.id.add_note_button); final TextView feeView = (TextView) view.findViewById(R.id.transaction_fee); final View feeViewContainer = view.findViewById(R.id.transaction_fee_container); final TextView valueNowView = (TextView) view.findViewById(R.id.transaction_value); final View valueNowContainerView = view.findViewById(R.id.transaction_value_container); String to = null; for (TransactionOutput output : tx.getOutputs()) { try { String toAddress = output.getScriptPubKey().getToAddress().toString(); if (!wallet.isAddressMine(toAddress)) { to = toAddress; } } catch (Exception e) { e.printStackTrace(); } } String from = null; for (TransactionInput input : tx.getInputs()) { try { String fromAddress = input.getFromAddress().toString(); if (!wallet.isAddressMine(fromAddress)) { from = fromAddress; } } catch (Exception e) { e.printStackTrace(); } } long realResult = 0; int confirmations = 0; if (tx instanceof MyTransaction) { MyTransaction myTx = (MyTransaction) tx; realResult = myTx.getResult().longValue(); if (wallet.getLatestBlock() != null) { confirmations = wallet.getLatestBlock().getHeight() - myTx.getHeight() + 1; } } else if (application.isInP2PFallbackMode()) { realResult = tx.getValue(application.bitcoinjWallet).longValue(); if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) confirmations = tx.getConfidence().getDepthInBlocks(); } final long finalResult = realResult; if (realResult <= 0) { toViewLabel.setText(R.string.transaction_fragment_to); if (to == null) { ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer); } else { toView.setText(to); } } else { toViewLabel.setText(R.string.transaction_fragment_from); if (from == null) { ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer); } else { toView.setText(from); } } //confirmations view if (confirmations > 0) { confirmationsView.setText("" + confirmations); } else { confirmationsView.setText("Unconfirmed"); } //Hash String view final String hashString = new String(Hex.encode(tx.getHash().getBytes()), "UTF-8"); hashView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https:/" + Constants.BLOCKCHAIN_DOMAIN + "/tx/" + hashString)); startActivity(browserIntent); } }); //Notes View String note = wallet.getTxNotes().get(hashString); if (note == null) { addNoteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); AddNoteDialog.showDialog(getFragmentManager(), hashString); } }); view.removeView(noteView); } else { view.removeView(addNoteButton); noteView.setText(note); noteView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); AddNoteDialog.showDialog(getFragmentManager(), hashString); } }); } addNoteButton.setEnabled(!application.isInP2PFallbackMode()); SpannableString content = new SpannableString(hashString); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); hashView.setText(content); if (realResult > 0 && from != null) resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_received, WalletUtils.formatValue(BigInteger.valueOf(realResult)))); else if (realResult < 0 && to != null) resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_sent, WalletUtils.formatValue(BigInteger.valueOf(realResult)))); else resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_moved, WalletUtils.formatValue(totalOutputValue))); final Date time = tx.getUpdateTime(); transactionTimeView.setText(dateFormat.format(time)); //These will be made visible again later once information is fetched from server feeViewContainer.setVisibility(View.GONE); valueNowContainerView.setVisibility(View.GONE); if (tx instanceof MyTransaction) { MyTransaction myTx = (MyTransaction) tx; final long txIndex = myTx.getTxIndex(); final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final JSONObject obj = getTransactionSummary(txIndex, wallet.getGUID(), finalResult); handler.post(new Runnable() { @Override public void run() { try { if (obj.get("fee") != null) { feeViewContainer.setVisibility(View.VISIBLE); feeView.setText(WalletUtils.formatValue( BigInteger.valueOf(Long.valueOf(obj.get("fee").toString()))) + " BTC"); } if (obj.get("confirmations") != null) { int confirmations = ((Number) obj.get("confirmations")).intValue(); confirmationsView.setText("" + confirmations); } String result_local = (String) obj.get("result_local"); String result_local_historical = (String) obj .get("result_local_historical"); if (result_local != null && result_local.length() > 0) { valueNowContainerView.setVisibility(View.VISIBLE); if (result_local_historical == null || result_local_historical.length() == 0 || result_local_historical.equals(result_local)) { valueNowView.setText(result_local); } else { valueNowView.setText(getString(R.string.value_now_ten, result_local, result_local_historical)); } } } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } catch (Exception e) { e.printStackTrace(); } Dialog d = dialog.create(); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.dimAmount = 0; lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; d.show(); d.getWindow().setAttributes(lp); d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return d; }
From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { MenuItem item = menu.add(Menu.NONE, ACTIONBAR_MENU_ITEM_FIILTER, Menu.NONE, getString(R.string.order_call_taxi_page_title)); SpannableString spanString = new SpannableString(item.getTitle().toString()); spanString.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spanString.length(), 0); //fix the color to white item.setTitle(spanString);/*from w ww .j a va2 s . c om*/ if (isShowOneKey) item.setVisible(true); else item.setVisible(false); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); super.onCreateOptionsMenu(menu, inflater); }
From source file:com.todoroo.astrid.tags.TagsControlSet.java
private Function<TagData, SpannableString> tagToString(final float maxLength) { return tagData -> { String tagName = tagData.getName(); tagName = tagName.substring(0, Math.min(tagName.length(), (int) maxLength)).replace(' ', NO_BREAK_SPACE);// w w w .jav a2 s .co m SpannableString string = new SpannableString(NO_BREAK_SPACE + tagName + NO_BREAK_SPACE); int themeIndex = tagData.getColor(); ThemeColor color = themeIndex >= 0 ? themeCache.getThemeColor(themeIndex) : themeCache.getUntaggedColor(); string.setSpan(new BackgroundColorSpan(color.getPrimaryColor()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); string.setSpan(new ForegroundColorSpan(color.getActionBarTint()), 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); return string; }; }
From source file:gov.wa.wsdot.android.wsdot.ui.tollrates.SR167TollRatesFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_dynamic_toll_rates, null); mRecyclerView = root.findViewById(R.id.my_recycler_view); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getActivity()); mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new SR167TollRatesItemAdapter(getActivity()); mRecyclerView.setAdapter(mAdapter);/* w w w . j a v a 2 s.c om*/ mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity())); mRecyclerView.setPadding(0, 0, 0, 120); addDisclaimerView(root); directionRadioGroup = root.findViewById(R.id.segment_control); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext()); radioGroupDirectionIndex = sharedPref.getInt(getString(R.string.toll_rates_167_travel_direction_key), 0); if (radioGroupDirectionIndex == 0) { RadioButton leftSegment = root.findViewById(R.id.radio_left); leftSegment.setChecked(true); } else { RadioButton rightSegment = root.findViewById(R.id.radio_right); rightSegment.setChecked(true); } directionRadioGroup.setOnCheckedChangeListener((group, checkedId) -> { RadioButton selectedDirection = directionRadioGroup.findViewById(checkedId); mAdapter.setData(filterTollsForDirection(String.valueOf(selectedDirection.getText().charAt(0)))); mLayoutManager.scrollToPositionWithOffset(0, 0); SharedPreferences sharedPref1 = PreferenceManager.getDefaultSharedPreferences(getContext()); SharedPreferences.Editor editor = sharedPref1.edit(); radioGroupDirectionIndex = directionRadioGroup.indexOfChild(selectedDirection); TextView travelTimeView = root.findViewById(R.id.travel_time_text); travelTimeView.setText(getTravelTimeStringForDirection(radioGroupDirectionIndex == 0 ? "N" : "S")); editor.putInt(getString(R.string.toll_rates_167_travel_direction_key), radioGroupDirectionIndex); editor.apply(); }); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); swipeRefreshLayout = root.findViewById(R.id.swipe_container); swipeRefreshLayout.setOnRefreshListener(this); swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light); mEmptyView = root.findViewById(R.id.empty_list_view); TextView header_link = root.findViewById(R.id.header_text); // create spannable string for underline SpannableString content = new SpannableString( getActivity().getResources().getString(R.string.sr167_info_link)); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); header_link.setText(content); header_link.setTextColor(getResources().getColor(R.color.primary_default)); header_link.setOnClickListener(v -> { Intent intent = new Intent(); // GA tracker mTracker = ((WsdotApplication) getActivity().getApplication()).getDefaultTracker(); mTracker.setScreenName("/Toll Rates/Learn about SR-167"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.wsdot.wa.gov/Tolling/SR167HotLanes/HOTtollrates.htm")); startActivity(intent); }); viewModel = ViewModelProviders.of(this, viewModelFactory).get(TollRatesViewModel.class); viewModel.getResourceStatus().observe(this, resourceStatus -> { if (resourceStatus != null) { switch (resourceStatus.status) { case LOADING: swipeRefreshLayout.setRefreshing(true); break; case SUCCESS: swipeRefreshLayout.setRefreshing(false); break; case ERROR: swipeRefreshLayout.setRefreshing(false); Toast.makeText(this.getContext(), "connection error", Toast.LENGTH_LONG).show(); } } }); viewModel.getSR167TollRateItems().observe(this, tollRateGroups -> { if (tollRateGroups != null) { mEmptyView.setVisibility(View.GONE); Collections.sort(tollRateGroups, new SortTollGroupByLocation()); Collections.sort(tollRateGroups, new SortTollGroupByDirection()); tollGroups = new ArrayList<>(tollRateGroups); directionRadioGroup.getCheckedRadioButtonId(); RadioButton selectedDirection = directionRadioGroup .findViewById(directionRadioGroup.getCheckedRadioButtonId()); mAdapter.setData(filterTollsForDirection(String.valueOf(selectedDirection.getText().charAt(0)))); } }); viewModel.getTravelTimesForETLFor("167").observe(this, travelTimes -> { TextView travelTimeView = root.findViewById(R.id.travel_time_text); if (travelTimes.size() > 0) { travelTimeView.setVisibility(View.VISIBLE); this.travelTimes = new ArrayList<>(travelTimes); travelTimeView.setText(getTravelTimeStringForDirection(radioGroupDirectionIndex == 0 ? "N" : "S")); } else { travelTimeView.setVisibility(View.GONE); } }); timer = new Timer(); timer.schedule(new SR167TollRatesFragment.RatesTimerTask(), 0, 60000); // Schedule rates to update every 60 seconds return root; }
From source file:au.org.ala.fielddata.mobile.CollectSurveyData.java
public void onSpeciesSelected(Species selectedSpecies) { surveyViewModel.speciesSelected(selectedSpecies); pager.setCurrentItem(1);//from w w w. j av a2 s .com SpannableString title = new SpannableString(selectedSpecies.scientificName); title.setSpan(new StyleSpan(Typeface.ITALIC), 0, title.length(), 0); getSupportActionBar().setTitle(title); getSupportActionBar().setSubtitle(selectedSpecies.commonName); }
From source file:li.barter.activities.AbstractBarterLiActivity.java
/** * Sets the Action bar title, using the desired {@link Typeface} loaded from {@link * TypefaceCache}//from w ww . j av a 2 s . com * * @param title The title to set for the Action Bar */ public final void setActionBarTitle(final String title) { final SpannableString s = new SpannableString(title); s.setSpan(new TypefacedSpan(this, TypefaceCache.SLAB_REGULAR), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Update the action bar title with the TypefaceSpan instance final ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(s); }
From source file:com.maxleapmobile.gitmaster.ui.fragment.RecommendFragment.java
private void initUI(View view) { actionArea = (LinearLayout) view.findViewById(R.id.recommend_action_area); starProgressBar = (ProgressBar) view.findViewById(R.id.recommend_star_progressbar); starText = (TextView) view.findViewById(R.id.recommend_star); starText.setOnClickListener(this); view.findViewById(R.id.recommend_fork).setOnClickListener(this); skipBtn = view.findViewById(R.id.recommend_skip); skipBtn.setOnClickListener(this); mProgressBar = (ProgressBar) view.findViewById(R.id.repo_progressbar); TextView notice2 = (TextView) view.findViewById(R.id.recommend_notice2); SpannableString notice2SS = new SpannableString(mContext.getString(R.string.recommend_notice2_part1) + " " + mContext.getString(R.string.recommend_notice2_part2)); notice2SS.setSpan(new CustomClickableSpan(), 0, mContext.getString(R.string.recommend_notice2_part1).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); notice2.setText(notice2SS);/*w w w. ja v a2 s .co m*/ notice2.setOnClickListener(this); notice3 = (TextView) view.findViewById(R.id.recommend_notice3); final SpannableString notice3SS = new SpannableString(mContext.getString(R.string.recommend_notice3_part1) + " " + mContext.getString(R.string.recommend_notice3_part2)); notice3SS.setSpan(new CustomClickableSpan(), mContext.getString(R.string.recommend_notice3_part1).length(), notice3SS.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); notice3.setText(notice3SS); notice3.setOnClickListener(this); mWebView = (ProgressWebView) view.findViewById(R.id.recommend_webview); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mProgressBar.setVisibility(View.GONE); } }); mEmptyView = (LinearLayout) view.findViewById(R.id.recommend_empty); mEmptyView.setVisibility(View.GONE); if (mParmasMap == null) { mParmasMap = new HashMap(); mParmasMap.put("userid", username); mParmasMap.put("page", page); mParmasMap.put("per_page", PER_PAGE); } }