Example usage for android.text.style StyleSpan StyleSpan

List of usage examples for android.text.style StyleSpan StyleSpan

Introduction

In this page you can find the example usage for android.text.style StyleSpan StyleSpan.

Prototype

public StyleSpan(@NonNull Parcel src) 

Source Link

Document

Creates a StyleSpan from a parcel.

Usage

From source file:com.mybitcoin.wallet.ui.TransactionsListFragment.java

@Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    final SpannableStringBuilder emptyText = new SpannableStringBuilder(
            getString(direction == Direction.SENT ? R.string.wallet_transactions_fragment_empty_text_sent
                    : R.string.wallet_transactions_fragment_empty_text_received));
    emptyText.setSpan(new StyleSpan(Typeface.BOLD), 0, emptyText.length(),
            SpannableStringBuilder.SPAN_POINT_MARK);
    /*if (direction != Direction.SENT)
       emptyText.append("\n\n").append(getString(R.string.wallet_transactions_fragment_empty_text_howto));*/

    setEmptyText(emptyText);//  w  w w  . ja  va2s  .co m
}

From source file:com.ubercab.client.feature.notification.handler.TripNotificationHandler.java

private NotificationCompat.InboxStyle buildStyleInbox(NotificationCompat.Builder paramBuilder,
          TripNotificationData paramTripNotificationData, String paramString) {
      NotificationCompat.InboxStyle localInboxStyle = new NotificationCompat.InboxStyle(paramBuilder)
              .setSummaryText(paramString);
      Iterator localIterator = paramTripNotificationData.getFareSplitClients().iterator();
      while (localIterator.hasNext()) {
          TripNotificationData.FareSplitClient localFareSplitClient = (TripNotificationData.FareSplitClient) localIterator
                  .next();//  www  .j  a  v  a2  s  .  c o  m
          SpannableString localSpannableString = new SpannableString(localFareSplitClient.getName());
          localSpannableString.setSpan(new StyleSpan(1), 0, localSpannableString.length(), 33);
          SpannableStringBuilder localSpannableStringBuilder = new SpannableStringBuilder();
          localSpannableStringBuilder.append(localSpannableString);
          localSpannableStringBuilder.append(" ");
          localSpannableStringBuilder.append(localFareSplitClient.getDisplayStatus(getContext()));
          localInboxStyle.addLine(localSpannableStringBuilder);
      }
      return localInboxStyle;
  }

From source file:com.gdgdevfest.android.apps.devfestbcn.ui.PlusStreamRowViewBinder.java

public static void bindActivityView(final View rootView, Activity activity, ImageLoader imageLoader,
        boolean singleSourceMode) {
    // Prepare view holder.
    ViewHolder tempViews = (ViewHolder) rootView.getTag();
    final ViewHolder views;
    if (tempViews != null) {
        views = tempViews;/*from   www. ja  va2 s  .c om*/
    } else {
        views = new ViewHolder();
        rootView.setTag(views);

        // Author and metadata box
        views.authorContainer = rootView.findViewById(R.id.stream_author_container);
        views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image);
        views.userName = (TextView) rootView.findViewById(R.id.stream_user_name);
        views.time = (TextView) rootView.findViewById(R.id.stream_time);

        // Author's content
        views.content = (TextView) rootView.findViewById(R.id.stream_content);

        // Original share box
        views.originalContainer = rootView.findViewById(R.id.stream_original_container);
        views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author);
        views.originalContent = (TextView) rootView.findViewById(R.id.stream_original_content);

        // Media box
        views.mediaContainer = rootView.findViewById(R.id.stream_media_container);
        views.mediaBackground = (ImageView) rootView.findViewById(R.id.stream_media_background);
        views.mediaOverlay = (ImageView) rootView.findViewById(R.id.stream_media_overlay);
        views.mediaTitle = (TextView) rootView.findViewById(R.id.stream_media_title);
        views.mediaSubtitle = (TextView) rootView.findViewById(R.id.stream_media_subtitle);

        // Interactions box
        views.interactionsContainer = rootView.findViewById(R.id.stream_interactions_container);
        views.plusOnes = (TextView) rootView.findViewById(R.id.stream_plus_ones);
        views.shares = (TextView) rootView.findViewById(R.id.stream_shares);
        views.comments = (TextView) rootView.findViewById(R.id.stream_comments);
    }

    final Context context = rootView.getContext();
    final Resources res = context.getResources();

    // Determine if this is a reshare (affects how activity fields are to be interpreted).
    Activity.PlusObject.Actor originalAuthor = activity.getObject().getActor();
    boolean isReshare = "share".equals(activity.getVerb()) && originalAuthor != null;

    // Author and metadata box
    views.authorContainer.setVisibility(singleSourceMode ? View.GONE : View.VISIBLE);
    views.userName.setText(activity.getActor().getDisplayName());

    // Find user profile image url
    String userImageUrl = null;
    if (activity.getActor().getImage() != null) {
        userImageUrl = activity.getActor().getImage().getUrl();
    }

    // Load image from network in background thread using Volley library
    imageLoader.get(userImageUrl, views.userImage, PLACEHOLDER_USER_IMAGE);

    long thenUTC = activity.getUpdated().getValue() + activity.getUpdated().getTimeZoneShift() * 60000;
    views.time.setText(DateUtils.getRelativeTimeSpanString(thenUTC, System.currentTimeMillis(),
            DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_RELATIVE));

    // Author's additional content
    String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent();
    views.content.setMaxLines(singleSourceMode ? 1000 : 5);
    if (!TextUtils.isEmpty(selfContent)) {
        views.content.setVisibility(View.VISIBLE);
        views.content.setText(Html.fromHtml(selfContent));
    } else {
        views.content.setVisibility(View.GONE);
    }

    // Original share box
    if (isReshare) {
        views.originalContainer.setVisibility(View.VISIBLE);

        // Set original author text, highlight author name
        final String author = res.getString(R.string.stream_originally_shared, originalAuthor.getDisplayName());
        final SpannableStringBuilder spannableAuthor = new SpannableStringBuilder(author);
        spannableAuthor.setSpan(new StyleSpan(Typeface.BOLD),
                author.length() - originalAuthor.getDisplayName().length(), author.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        views.originalAuthor.setText(spannableAuthor, TextView.BufferType.SPANNABLE);

        String originalContent = activity.getObject().getContent();
        views.originalContent.setMaxLines(singleSourceMode ? 1000 : 3);
        if (!TextUtils.isEmpty(originalContent)) {
            views.originalContent.setVisibility(View.VISIBLE);
            views.originalContent.setText(Html.fromHtml(originalContent));
        } else {
            views.originalContent.setVisibility(View.GONE);
        }
    } else {
        views.originalContainer.setVisibility(View.GONE);
    }

    // Media box

    // Set media content.
    List<Activity.PlusObject.Attachments> attachments = activity.getObject().getAttachments();
    if (attachments != null && attachments.size() > 0) {
        Activity.PlusObject.Attachments attachment = attachments.get(0);
        String objectType = attachment.getObjectType();
        String imageUrl = attachment.getImage() != null ? attachment.getImage().getUrl() : null;
        if (imageUrl == null && attachment.getThumbnails() != null && attachment.getThumbnails().size() > 0) {
            Thumbnails thumb = attachment.getThumbnails().get(0);
            imageUrl = thumb.getImage() != null ? thumb.getImage().getUrl() : null;
        }

        // Load image from network in background thread using Volley library
        imageLoader.get(imageUrl, views.mediaBackground, PLACEHOLDER_MEDIA_IMAGE);

        boolean overlayStyle = false;

        views.mediaOverlay.setImageDrawable(null);
        if (("photo".equals(objectType) || "video".equals(objectType) || "album".equals(objectType))
                && !TextUtils.isEmpty(imageUrl)) {
            overlayStyle = true;
            views.mediaOverlay
                    .setImageResource("video".equals(objectType) ? R.drawable.ic_stream_media_overlay_video
                            : R.drawable.ic_stream_media_overlay_photo);

        } else if ("article".equals(objectType) || "event".equals(objectType)) {
            overlayStyle = false;
            views.mediaTitle.setText(attachment.getDisplayName());
            if (!TextUtils.isEmpty(attachment.getUrl())) {
                Uri uri = Uri.parse(attachment.getUrl());
                views.mediaSubtitle.setText(uri.getHost());
            } else {
                views.mediaSubtitle.setText("");
            }
        }

        views.mediaContainer.setVisibility(View.VISIBLE);
        views.mediaContainer.setBackgroundResource(
                overlayStyle ? R.color.plus_stream_media_background : android.R.color.black);
        if (overlayStyle) {
            views.mediaBackground.clearColorFilter();
        } else {
            views.mediaBackground.setColorFilter(res.getColor(R.color.plus_media_item_tint));
        }
        views.mediaOverlay.setVisibility(overlayStyle ? View.VISIBLE : View.GONE);
        views.mediaTitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE);
        views.mediaSubtitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE);
    } else {
        views.mediaContainer.setVisibility(View.GONE);
        views.mediaBackground.setImageDrawable(null);
        views.mediaOverlay.setImageDrawable(null);
    }

    // Interactions box
    final int plusOneCount = (activity.getObject().getPlusoners() != null)
            ? activity.getObject().getPlusoners().getTotalItems().intValue()
            : 0;
    if (plusOneCount > 0) {
        views.plusOnes.setVisibility(View.VISIBLE);
        views.plusOnes.setText(getPlusOneString(plusOneCount));
    } else {
        views.plusOnes.setVisibility(View.GONE);
    }

    final int commentCount = (activity.getObject().getReplies() != null)
            ? activity.getObject().getReplies().getTotalItems().intValue()
            : 0;
    if (commentCount > 0) {
        views.comments.setVisibility(View.VISIBLE);
        views.comments.setText(Integer.toString(commentCount));
    } else {
        views.comments.setVisibility(View.GONE);
    }

    final int resharerCount = (activity.getObject().getResharers() != null)
            ? activity.getObject().getResharers().getTotalItems().intValue()
            : 0;
    if (resharerCount > 0) {
        views.shares.setVisibility(View.VISIBLE);
        views.shares.setText(Integer.toString(resharerCount));
    } else {
        views.shares.setVisibility(View.GONE);
    }

    views.interactionsContainer.setVisibility(
            (plusOneCount > 0 || commentCount > 0 || resharerCount > 0) ? View.VISIBLE : View.GONE);
}

From source file:com.benext.thibault.appsample.notification.builder.NotificationBuilder.java

private static Spannable getSpannableString(Context context, int strId, int typeface) {

    Spannable startersTitle = new SpannableString(context.getString(strId));
    startersTitle.setSpan(new StyleSpan(typeface), 0, startersTitle.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return startersTitle;
}

From source file:org.sufficientlysecure.keychain.ui.adapter.SubkeysAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView vKeyId = (TextView) view.findViewById(R.id.subkey_item_key_id);
    TextView vKeyDetails = (TextView) view.findViewById(R.id.subkey_item_details);
    TextView vKeyExpiry = (TextView) view.findViewById(R.id.subkey_item_expiry);
    ImageView vCertifyIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_certify);
    ImageView vSignIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_sign);
    ImageView vEncryptIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_encrypt);
    ImageView vAuthenticateIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_authenticate);
    ImageView vEditImage = (ImageView) view.findViewById(R.id.subkey_item_edit_image);
    ImageView vStatus = (ImageView) view.findViewById(R.id.subkey_item_status);

    // not used:/*from   w w  w.java2  s .  com*/
    ImageView deleteImage = (ImageView) view.findViewById(R.id.subkey_item_delete_button);
    deleteImage.setVisibility(View.GONE);

    long keyId = cursor.getLong(INDEX_KEY_ID);
    vKeyId.setText(KeyFormattingUtils.beautifyKeyId(keyId));

    // may be set with additional "stripped" later on
    SpannableStringBuilder algorithmStr = new SpannableStringBuilder();
    algorithmStr.append(KeyFormattingUtils.getAlgorithmInfo(context, cursor.getInt(INDEX_ALGORITHM),
            cursor.getInt(INDEX_KEY_SIZE), cursor.getString(INDEX_KEY_CURVE_OID)));

    SubkeyChange change = mSaveKeyringParcel != null ? mSaveKeyringParcel.getSubkeyChange(keyId) : null;

    if (change != null && (change.mDummyStrip || change.mMoveKeyToSecurityToken)) {
        if (change.mDummyStrip) {
            algorithmStr.append(", ");
            final SpannableString boldStripped = new SpannableString(context.getString(R.string.key_stripped));
            boldStripped.setSpan(new StyleSpan(Typeface.BOLD), 0, boldStripped.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            algorithmStr.append(boldStripped);
        }
        if (change.mMoveKeyToSecurityToken) {
            algorithmStr.append(", ");
            final SpannableString boldDivert = new SpannableString(context.getString(R.string.key_divert));
            boldDivert.setSpan(new StyleSpan(Typeface.BOLD), 0, boldDivert.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            algorithmStr.append(boldDivert);
        }
    } else {
        switch (SecretKeyType.fromNum(cursor.getInt(INDEX_HAS_SECRET))) {
        case GNU_DUMMY:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_stripped));
            break;
        case DIVERT_TO_CARD:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_divert));
            break;
        case PASSPHRASE_EMPTY:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_no_passphrase));
            break;
        case UNAVAILABLE:
            // don't show this on pub keys
            //algorithmStr += ", " + context.getString(R.string.key_unavailable);
            break;
        }
    }
    vKeyDetails.setText(algorithmStr, TextView.BufferType.SPANNABLE);

    boolean isMasterKey = cursor.getInt(INDEX_RANK) == 0;
    if (isMasterKey) {
        vKeyId.setTypeface(null, Typeface.BOLD);
    } else {
        vKeyId.setTypeface(null, Typeface.NORMAL);
    }

    // Set icons according to properties
    vCertifyIcon.setVisibility(cursor.getInt(INDEX_CAN_CERTIFY) != 0 ? View.VISIBLE : View.GONE);
    vEncryptIcon.setVisibility(cursor.getInt(INDEX_CAN_ENCRYPT) != 0 ? View.VISIBLE : View.GONE);
    vSignIcon.setVisibility(cursor.getInt(INDEX_CAN_SIGN) != 0 ? View.VISIBLE : View.GONE);
    vAuthenticateIcon.setVisibility(cursor.getInt(INDEX_CAN_AUTHENTICATE) != 0 ? View.VISIBLE : View.GONE);

    boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0;

    Date expiryDate = null;
    if (!cursor.isNull(INDEX_EXPIRY)) {
        expiryDate = new Date(cursor.getLong(INDEX_EXPIRY) * 1000);
    }

    // for edit key
    if (mSaveKeyringParcel != null) {
        boolean revokeThisSubkey = (mSaveKeyringParcel.mRevokeSubKeys.contains(keyId));

        if (revokeThisSubkey) {
            if (!isRevoked) {
                isRevoked = true;
            }
        }

        SaveKeyringParcel.SubkeyChange subkeyChange = mSaveKeyringParcel.getSubkeyChange(keyId);
        if (subkeyChange != null) {
            if (subkeyChange.mExpiry == null || subkeyChange.mExpiry == 0L) {
                expiryDate = null;
            } else {
                expiryDate = new Date(subkeyChange.mExpiry * 1000);
            }
        }

        vEditImage.setVisibility(View.VISIBLE);
    } else {
        vEditImage.setVisibility(View.GONE);
    }

    boolean isExpired;
    if (expiryDate != null) {
        isExpired = expiryDate.before(new Date());
        Calendar expiryCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        expiryCal.setTime(expiryDate);
        // convert from UTC to time zone of device
        expiryCal.setTimeZone(TimeZone.getDefault());

        vKeyExpiry.setText(context.getString(R.string.label_expiry) + ": "
                + DateFormat.getDateFormat(context).format(expiryCal.getTime()));
    } else {
        isExpired = false;

        vKeyExpiry.setText(context.getString(R.string.label_expiry) + ": " + context.getString(R.string.none));
    }

    // if key is expired or revoked...
    boolean isInvalid = isRevoked || isExpired;
    if (isInvalid) {
        vStatus.setVisibility(View.VISIBLE);

        vCertifyIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vSignIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vEncryptIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vAuthenticateIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);

        if (isRevoked) {
            vStatus.setImageResource(R.drawable.status_signature_revoked_cutout_24dp);
            vStatus.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                    PorterDuff.Mode.SRC_IN);
        } else if (isExpired) {
            vStatus.setImageResource(R.drawable.status_signature_expired_cutout_24dp);
            vStatus.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                    PorterDuff.Mode.SRC_IN);
        }
    } else {
        vStatus.setVisibility(View.GONE);

        vKeyId.setTextColor(mDefaultTextColor);
        vKeyDetails.setTextColor(mDefaultTextColor);
        vKeyExpiry.setTextColor(mDefaultTextColor);

        vCertifyIcon.clearColorFilter();
        vSignIcon.clearColorFilter();
        vEncryptIcon.clearColorFilter();
        vAuthenticateIcon.clearColorFilter();
    }
    vKeyId.setEnabled(!isInvalid);
    vKeyDetails.setEnabled(!isInvalid);
    vKeyExpiry.setEnabled(!isInvalid);
}

From source file:net.kourlas.voipms_sms.adapters.ConversationsRecyclerViewAdapter.java

@Override
public void onBindViewHolder(ConversationViewHolder conversationViewHolder, int position) {
    Message message = messages.get(position);

    ViewSwitcher viewSwitcher = conversationViewHolder.getViewSwitcher();
    viewSwitcher.setDisplayedChild(isItemChecked(position) ? 1 : 0);

    QuickContactBadge contactBadge = conversationViewHolder.getContactBadge();
    contactBadge.assignContactFromPhone(message.getContact(), true);

    String photoUri = Utils.getContactPhotoUri(applicationContext, message.getContact());
    if (photoUri != null) {
        contactBadge.setImageURI(Uri.parse(photoUri));
    } else {//from  www. j  av  a2  s . c  o  m
        contactBadge.setImageToDefault();
    }

    TextView contactTextView = conversationViewHolder.getContactTextView();
    String contactName = Utils.getContactName(applicationContext, message.getContact());
    SpannableStringBuilder contactTextBuilder = new SpannableStringBuilder();
    if (contactName != null) {
        contactTextBuilder.append(contactName);
    } else {
        contactTextBuilder.append(Utils.getFormattedPhoneNumber(message.getContact()));
    }
    if (!filterConstraint.equals("")) {
        int index = contactTextBuilder.toString().toLowerCase().indexOf(filterConstraint.toLowerCase());
        if (index != -1) {
            contactTextBuilder.setSpan(
                    new BackgroundColorSpan(ContextCompat.getColor(applicationContext, R.color.highlight)),
                    index, index + filterConstraint.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        }
    }
    contactTextView.setText(contactTextBuilder);

    final TextView messageTextView = conversationViewHolder.getMessageTextView();
    SpannableStringBuilder messageTextBuilder = new SpannableStringBuilder();

    int index = message.getText().toLowerCase().indexOf(filterConstraint.toLowerCase());
    if (!filterConstraint.equals("") && index != -1) {
        int nonMessageOffset = index;
        if (message.getType() == Message.Type.OUTGOING) {
            messageTextBuilder.insert(0,
                    applicationContext.getString(R.string.conversations_message_you) + " ");
            nonMessageOffset += 5;
        }

        int substringOffset = index - 20;
        if (substringOffset > 0) {
            messageTextBuilder.append("...");
            nonMessageOffset += 3;

            while (message.getText().charAt(substringOffset) != ' ' && substringOffset < index - 1) {
                substringOffset += 1;
            }
            substringOffset += 1;
        } else {
            substringOffset = 0;
        }

        messageTextBuilder.append(message.getText().substring(substringOffset));
        messageTextBuilder.setSpan(
                new BackgroundColorSpan(ContextCompat.getColor(applicationContext, R.color.highlight)),
                nonMessageOffset - substringOffset,
                nonMessageOffset - substringOffset + filterConstraint.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
    } else {
        if (message.getType() == Message.Type.OUTGOING) {
            messageTextBuilder.append(applicationContext.getString(R.string.conversations_message_you));
            messageTextBuilder.append(" ");
        }
        messageTextBuilder.append(message.getText());
    }
    messageTextView.setText(messageTextBuilder);

    if (message.isUnread()) {
        contactTextView.setTypeface(null, Typeface.BOLD);
        messageTextView.setTypeface(null, Typeface.BOLD);
    } else {
        contactTextView.setTypeface(null, Typeface.NORMAL);
        messageTextView.setTypeface(null, Typeface.NORMAL);
    }

    // Set date line
    TextView dateTextView = conversationViewHolder.getDateTextView();
    if (message.isDraft()) {
        SpannableStringBuilder dateTextBuilder = new SpannableStringBuilder();
        dateTextBuilder.append(applicationContext.getString(R.string.conversations_message_draft));
        dateTextBuilder.setSpan(new StyleSpan(Typeface.ITALIC), 0, dateTextBuilder.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        dateTextView.setText(dateTextBuilder);
    } else if (!message.isDelivered()) {
        if (!message.isDeliveryInProgress()) {
            SpannableStringBuilder dateTextBuilder = new SpannableStringBuilder();
            dateTextBuilder.append(applicationContext.getString(R.string.conversations_message_not_sent));
            dateTextBuilder.setSpan(
                    new ForegroundColorSpan(
                            ContextCompat.getColor(applicationContext, android.R.color.holo_red_dark)),
                    0, dateTextBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            dateTextView.setText(dateTextBuilder);
        } else {
            dateTextView.setText(applicationContext.getString(R.string.conversations_message_sending));
        }
    } else {
        dateTextView.setText(Utils.getFormattedDate(applicationContext, message.getDate(), true));
    }
}

From source file:org.sirimangalo.meditationplus.AdapterCommit.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_item_commit, parent, false);

    final View shell = rowView.findViewById(R.id.detail_shell);

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override/*from  w ww. j av  a2 s  .co m*/
        public void onClick(View view) {
            boolean visible = shell.getVisibility() == View.VISIBLE;

            shell.setVisibility(visible ? View.GONE : View.VISIBLE);

            context.setCommitVisible(position, !visible);

        }
    });

    final JSONObject p = values.get(position);

    TextView title = (TextView) rowView.findViewById(R.id.title);
    TextView descV = (TextView) rowView.findViewById(R.id.desc);
    TextView defV = (TextView) rowView.findViewById(R.id.def);
    TextView usersV = (TextView) rowView.findViewById(R.id.users);
    TextView youV = (TextView) rowView.findViewById(R.id.you);

    try {

        if (p.getBoolean("open"))
            shell.setVisibility(View.VISIBLE);

        title.setText(p.getString("title"));
        descV.setText(p.getString("description"));

        String length = p.getString("length");
        String time = p.getString("time");
        final String cid = p.getString("cid");

        String def = "";

        boolean repeat = false;

        if (length.indexOf(":") > 0) {
            repeat = true;
            String[] lengtha = length.split(":");
            def += lengtha[0] + " minutes walking and " + lengtha[1] + " minutes sitting";
        } else
            def += length + " minutes total meditation";

        String period = p.getString("period");

        String day = p.getString("day");

        if (period.equals("daily")) {
            if (repeat)
                def += " every day";
            else
                def += " per day";
        } else if (period.equals("weekly")) {
            if (repeat)
                def += " every " + dow[Integer.parseInt(day)];
            else
                def += " per week";
        } else if (period.equals("monthly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the month";
            else
                def += " per month";
        } else if (period.equals("yearly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the year";
            else
                def += " per year";
        }

        if (!time.equals("any")) {
            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
            utc.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

            Calendar here = Calendar.getInstance();
            here.setTimeInMillis(utc.getTimeInMillis());

            int hours = here.get(Calendar.HOUR_OF_DAY);
            int minutes = here.get(Calendar.MINUTE);

            def += " at " + (time.length() == 4 ? "0" : "") + time.replace(":", "") + "h UTC <i>("
                    + (hours > 12 ? hours - 12 : hours) + ":" + ((minutes < 10 ? "0" : "") + minutes) + " "
                    + (hours > 11 && hours < 24 ? "PM" : "AM") + " your time)</i>";
        }

        defV.setText(Html.fromHtml(def));

        JSONObject usersJ = p.getJSONObject("users");

        ArrayList<String> committedArray = new ArrayList<String>();

        // collect into array

        for (int i = 0; i < usersJ.names().length(); i++) {
            try {
                String j = usersJ.names().getString(i);
                String k = j;
                //                    if(j.equals(p.getString("creator")))
                //                        k = "["+j+"]";
                committedArray.add(k);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String text = context.getString(R.string.committed) + " ";

        // add spans

        int committed = -1;

        int pos = text.length(); // start after "Committed: "

        text += TextUtils.join(", ", committedArray);
        Spannable span = new SpannableString(text);

        span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: "

        for (int i = 0; i < committedArray.size(); i++) {
            try {

                final String oneCom = committedArray.get(i);
                String userCom = usersJ.getString(oneCom);
                //String userCom = usersJ.getString(oneCom.replace("[", "").replace("]", ""));

                //if(oneCom.replace("[","").replace("]","").equals(loggedUser))
                if (oneCom.equals(loggedUser))
                    committed = Integer.parseInt(userCom);

                int end = pos + oneCom.length();

                ClickableSpan clickable = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        context.showProfile(oneCom);
                    }

                };
                span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                span.setSpan(new UnderlineSpan() {
                    public void updateDrawState(TextPaint tp) {
                        tp.setUnderlineText(false);
                    }
                }, pos, end, 0);

                String color = Utils.makeRedGreen(Integer.parseInt(userCom), true);

                span.setSpan(new ForegroundColorSpan(Color.parseColor("#FF" + color)), pos, end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                pos += oneCom.length() + 2;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        usersV.setText(span);
        usersV.setMovementMethod(new LinkMovementMethod());

        if (loggedUser != null && loggedUser.length() > 0) {
            LinearLayout bl = (LinearLayout) rowView.findViewById(R.id.commit_buttons);
            if (!usersJ.has(loggedUser)) {
                Button commitB = new Button(context);
                commitB.setId(R.id.commit_button);
                commitB.setText(R.string.commit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("commitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            } else {
                Button commitB = new Button(context);
                commitB.setId(R.id.uncommit_button);
                commitB.setText(R.string.uncommit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("uncommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            }

            if (loggedUser.equals(p.getString("creator")) || context.isAdmin) {
                Button commitB2 = new Button(context);
                commitB2.setId(R.id.edit_commit_button);
                commitB2.setText(R.string.edit);
                commitB2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(context, ActivityCommit.class);
                        i.putExtra("commitment", p.toString());
                        context.startActivity(i);
                    }
                });
                bl.addView(commitB2);

                Button commitB3 = new Button(context);
                commitB3.setId(R.id.uncommit_button);
                commitB3.setText(R.string.delete);
                commitB3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("delcommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB3);
            }

        }

        if (committed > -1) {
            int color = Color.parseColor("#FF" + Utils.makeRedGreen(committed, false));
            rowView.setBackgroundColor(color);
        }

        if (committed != -1) {
            youV.setText(String.format(context.getString(R.string.you_commit_x), committed));
            youV.setVisibility(View.VISIBLE);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

From source file:org.mozilla.gecko.AboutHomeContent.java

public void init() {
    Context context = getContext();
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mInflater.inflate(R.layout.abouthome_content, this);

    mAccountManager = AccountManager.get(context);

    // The listener will run on the background thread (see 2nd argument)
    mAccountManager.addOnAccountsUpdatedListener(new OnAccountsUpdateListener() {
        public void onAccountsUpdated(Account[] accounts) {
            final GeckoApp.StartupMode startupMode = GeckoApp.mAppContext.getStartupMode();
            final boolean syncIsSetup = isSyncSetup();

            GeckoApp.mAppContext.mMainHandler.post(new Runnable() {
                public void run() {
                    // The listener might run before the UI is initially updated.
                    // In this case, we should simply wait for the initial setup
                    // to happen.
                    if (mTopSitesAdapter != null)
                        updateLayout(startupMode, syncIsSetup);
                }//from   w  w  w.j ava2 s .  co m
            });
        }
    }, GeckoAppShell.getHandler(), false);

    mTopSitesGrid = (GridView) findViewById(R.id.top_sites_grid);
    mTopSitesGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Cursor c = (Cursor) parent.getItemAtPosition(position);

            String spec = c.getString(c.getColumnIndex(URLColumns.URL));
            Log.i(LOGTAG, "clicked: " + spec);

            if (mUriLoadCallback != null)
                mUriLoadCallback.callback(spec);
        }
    });

    mAddonsLayout = (LinearLayout) findViewById(R.id.recommended_addons);
    mLastTabsLayout = (LinearLayout) findViewById(R.id.last_tabs);

    TextView allTopSitesText = (TextView) findViewById(R.id.all_top_sites_text);
    allTopSitesText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            GeckoApp.mAppContext.showAwesomebar(AwesomeBar.Type.EDIT);
        }
    });

    TextView allAddonsText = (TextView) findViewById(R.id.all_addons_text);
    allAddonsText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (mUriLoadCallback != null)
                mUriLoadCallback.callback("https://addons.mozilla.org/android");
        }
    });

    TextView syncTextView = (TextView) findViewById(R.id.sync_text);
    String syncText = syncTextView.getText().toString() + " \u00BB";
    String boldName = getContext().getResources().getString(R.string.abouthome_sync_bold_name);
    int styleIndex = syncText.indexOf(boldName);

    // Highlight any occurrence of "Firefox Sync" in the string
    // with a bold style.
    if (styleIndex >= 0) {
        SpannableString spannableText = new SpannableString(syncText);
        spannableText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), styleIndex, styleIndex + 12, 0);
        syncTextView.setText(spannableText, TextView.BufferType.SPANNABLE);
    }

    RelativeLayout syncBox = (RelativeLayout) findViewById(R.id.sync_box);
    syncBox.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Context context = v.getContext();
            Intent intent = new Intent(context, SetupSyncActivity.class);
            context.startActivity(intent);
        }
    });
}

From source file:com.android.example.notificationshowcase.NotificationService.java

@Override
protected void onHandleIntent(Intent intent) {
    ArrayList<Notification> mNotifications = new ArrayList<Notification>();
    NotificationManager noMa = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    int bigtextId = mNotifications.size();
    mNotifications.add(makeBigTextNotification(this, 0, bigtextId, System.currentTimeMillis()));

    int uploadId = mNotifications.size();
    long uploadWhen = System.currentTimeMillis();
    mNotifications.add(makeUploadNotification(this, 10, uploadWhen));

    Notification phoneCall = new NotificationCompat.Builder(this).setContentTitle("Incoming call")
            .setContentText("Matias Duarte").setLargeIcon(getBitmap(this, R.drawable.matias_hed))
            .setSmallIcon(R.drawable.stat_sys_phone_call).setDefaults(Notification.DEFAULT_SOUND)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(ToastService.getPendingIntent(this, "Clicked on Matias"))
            .addAction(R.drawable.ic_dial_action_call, "Answer",
                    ToastService.getPendingIntent(this, "call answered"))
            .addAction(R.drawable.ic_end_call, "Ignore", ToastService.getPendingIntent(this, "call ignored"))
            .setAutoCancel(true).build();
    phoneCall.flags |= Notification.FLAG_INSISTENT;
    mNotifications.add(phoneCall);//from w  w  w. j  a v a 2 s .c o  m

    mNotifications.add(
            new NotificationCompat.Builder(this).setContentTitle("Stopwatch PRO").setContentText("Counting up")
                    .setContentIntent(ToastService.getPendingIntent(this, "Clicked on Stopwatch"))
                    .setSmallIcon(R.drawable.stat_notify_alarm).setUsesChronometer(true).build());

    mNotifications.add(
            new NotificationCompat.Builder(this).setContentTitle("J Planning").setContentText("The Botcave")
                    .setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.stat_notify_calendar)
                    .setContentIntent(ToastService.getPendingIntent(this, "Clicked on calendar event"))
                    .setContentInfo("7PM")
                    .addAction(R.drawable.stat_notify_snooze, "+10 min",
                            ToastService.getPendingIntent(this, "snoozed 10 min"))
                    .addAction(R.drawable.stat_notify_snooze_longer, "+1 hour",
                            ToastService.getPendingIntent(this, "snoozed 1 hr"))
                    .addAction(R.drawable.stat_notify_email, "Email",
                            makeEmailIntent(this, "gabec@example.com,mcleron@example.com,dsandler@example.com"))
                    .build());

    BitmapDrawable d = (BitmapDrawable) getResources().getDrawable(R.drawable.romainguy_rockaway);
    mNotifications.add(new NotificationCompat.BigPictureStyle(new NotificationCompat.Builder(this)
            .setContentTitle("Romain Guy")
            .setContentText("I was lucky to find a Canon 5D Mk III at a local Bay Area "
                    + "store last week but I had not been able to try it in the field "
                    + "until tonight. After a few days of rain the sky finally cleared "
                    + "up. Rockaway Beach did not disappoint and I was finally able to "
                    + "see what my new camera feels like when shooting landscapes.")
            .setSmallIcon(R.drawable.ic_stat_gplus)
            .setContentIntent(ToastService.getPendingIntent(this, "Clicked on bigPicture"))
            .setLargeIcon(getBitmap(this, R.drawable.romainguy_hed))
            .addAction(R.drawable.add, "Add to Gallery",
                    ToastService.getPendingIntent(this, "added! (just kidding)"))
            .setSubText("talk rocks!")).bigPicture(d.getBitmap()).build());

    // Note: this may conflict with real email notifications
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    SpannableString line1 = new SpannableString("Alice: hey there!");
    line1.setSpan(bold, 0, 5, 0);
    SpannableString line2 = new SpannableString("Bob: hi there!");
    line2.setSpan(bold, 0, 3, 0);
    SpannableString line3 = new SpannableString("Charlie: Iz IN UR EMAILZ!!");
    line3.setSpan(bold, 0, 7, 0);
    mNotifications.add(new NotificationCompat.InboxStyle(
            new NotificationCompat.Builder(this).setContentTitle("24 new messages")
                    .setContentText("You have mail!").setSubText("test.hugo2@gmail.com")
                    .setContentIntent(ToastService.getPendingIntent(this, "Clicked on Email"))
                    .setSmallIcon(R.drawable.stat_notify_email)).setSummaryText("+21 more").addLine(line1)
                            .addLine(line2).addLine(line3).build());

    mNotifications
            .add(new NotificationCompat.Builder(this).setContentTitle("Twitter").setContentText("New mentions")
                    .setContentIntent(ToastService.getPendingIntent(this, "Clicked on Twitter"))
                    .setSmallIcon(R.drawable.twitter_icon).setNumber(15)
                    .setPriority(NotificationCompat.PRIORITY_LOW).build());

    for (int i = 0; i < mNotifications.size(); i++) {
        noMa.notify(NOTIFICATION_ID + i, mNotifications.get(i));
    }

    ProgressService.startProgressUpdater(this, uploadId, uploadWhen, 0);
}

From source file:com.hannesdorfmann.home.HomeActivity.java

private void setNoFiltersVisiblity(int visibility) {
    if (visibility == View.VISIBLE) {
        if (noFiltersEmptyText == null) {
            // create the no filters empty text
            ViewStub stub = (ViewStub) findViewById(R.id.stub_no_filters);
            noFiltersEmptyText = (TextView) stub.inflate();
            String emptyText = getString(R.string.no_filters_selected);
            int filterPlaceholderStart = emptyText.indexOf('\u08B4');
            int altMethodStart = filterPlaceholderStart + 3;
            SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText);
            // show an image of the filter icon
            ssb.setSpan(new ImageSpan(this, R.drawable.ic_filter_small, ImageSpan.ALIGN_BASELINE),
                    filterPlaceholderStart, filterPlaceholderStart + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // make the alt method (swipe from right) less prominent and italic
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_secondary_light)),
                    altMethodStart, emptyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new StyleSpan(Typeface.ITALIC), altMethodStart, emptyText.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            noFiltersEmptyText.setText(ssb);
            noFiltersEmptyText.setOnClickListener(new View.OnClickListener() {
                @Override//from   w w  w. j ava  2  s.  c  om
                public void onClick(View v) {
                    drawer.openDrawer(GravityCompat.END);
                }
            });
        }
        noFiltersEmptyText.setVisibility(visibility);
    } else if (noFiltersEmptyText != null) {
        noFiltersEmptyText.setVisibility(visibility);
    }
}