Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:cmput301.f13t01.elasticsearch.ESClient.java

private <T> void postData(T data, HttpPost httpPost) throws IllegalStateException, IOException {

    StringEntity stringentity = null;/*w w  w.  jav a 2  s .  c  o  m*/
    try {
        String test = gson.toJson(data);
        String str = "I've Got a Lovely Bunch of Coconuts";
        String str_e = gson.toJson(new Text(new SpannableString(str)));
        Log.d("PUBLISH", "test: " + str_e);
        if (!test.equals(data)) {
            Log.d("PUBLISH", "Gson different from string");
        }
        Log.d("PUBLISH", "gson: " + test);
        Log.d("PUBLISH", "size: " + test.length());
        stringentity = new StringEntity(test);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    httpPost.setHeader("Accept", "application/json");

    httpPost.setEntity(stringentity);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpPost);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.d("PUBLISH", "Made it past execute");

    String status = response.getStatusLine().toString();
    System.out.println(status);
    HttpEntity entity = response.getEntity();
    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
    String output;
    System.err.println("Output from Server -> ");
    while ((output = br.readLine()) != null) {
        System.err.println(output);
    }

    try {
        entity.consumeContent();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return;
}

From source file:com.android.deskclock.Utils.java

/**
 * @param context - context used to get time format string resource
 * @param showAmPm - include the am/pm string if true
 * @return format string for 12 hours mode time
 *///from w ww  .ja  v a  2s  .  c om
public static CharSequence get12ModeFormat(Context context, boolean showAmPm) {
    String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "hma");
    if (!showAmPm) {
        pattern = pattern.replaceAll("a", "").trim();
    }

    // Replace spaces with "Hair Space"
    pattern = pattern.replaceAll(" ", "\u200A");
    // Build a spannable so that the am/pm will be formatted
    int amPmPos = pattern.indexOf('a');
    if (amPmPos == -1) {
        return pattern;
    }

    final Resources resources = context.getResources();
    final float amPmProportion = resources.getFraction(R.fraction.ampm_font_size_scale, 1, 1);
    final Spannable sp = new SpannableString(pattern);
    sp.setSpan(new RelativeSizeSpan(amPmProportion), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(new StyleSpan(Typeface.NORMAL), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(new TypefaceSpan("sans-serif"), amPmPos, amPmPos + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Make the font smaller for locales with long am/pm strings.
    if (Utils.isAmPmStringLong()) {
        final float proportion = resources.getFraction(R.fraction.reduced_clock_font_size_scale, 1, 1);
        sp.setSpan(new RelativeSizeSpan(proportion), 0, pattern.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return sp;
}

From source file:info.guardianproject.otr.app.im.app.MessageView.java

public void bindOutgoingMessage(int id, int messageType, String address, final String mimeType,
        final String body, Date date, Markup smileyRes, boolean scrolling, DeliveryState delivery,
        EncryptionState encryption) {//from  ww  w  .j ava 2  s  . c  om

    mHolder = (ViewHolder) getTag();

    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.resetOnClickListenerMediaThumbnail();
    if (mimeType != null) {

        lastMessage = "";
        Uri mediaUri = Uri.parse(body);

        showMediaThumbnail(mimeType, mediaUri, id, mHolder);

        mHolder.mTextViewForMessages.setVisibility(View.GONE);
        mHolder.mMediaThumbnail.setVisibility(View.VISIBLE);

    } else {
        mHolder.mMediaThumbnail.setVisibility(View.GONE);
        lastMessage = body;//formatMessage(body);

        try {

            SpannableString spannablecontent = new SpannableString(lastMessage);

            EmojiManager.getInstance(getContext()).addEmoji(getContext(), spannablecontent);

            mHolder.mTextViewForMessages.setText(spannablecontent);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (date != null) {

        CharSequence tsText = null;

        if (isSameDay(date, DATE_NOW))
            tsText = formatTimeStamp(date, messageType, MESSAGE_TIME_FORMAT, delivery, encryption);
        else
            tsText = formatTimeStamp(date, messageType, MESSAGE_DATETIME_FORMAT, delivery, encryption);

        mHolder.mTextViewForTimestamp.setText(tsText);

        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {
        mHolder.mTextViewForTimestamp.setText("");

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}

From source file:com.todoroo.astrid.adapter.TaskAdapter.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));
        SpannableString string = new SpannableString(SPACE + tagName + 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;
    };// w w  w. j  ava2 s  . c  om
}

From source file:io.plaidapp.designernews.ui.story.StoryActivity.java

private CharSequence getStoryPosterTimeText(String userDisplayName, String userJob, Date createdAt) {
    SpannableString poster = new SpannableString(userDisplayName.toLowerCase());
    poster.setSpan(new TextAppearanceSpan(this, io.plaidapp.R.style.TextAppearance_CommentAuthor), 0,
            poster.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    CharSequence job = !TextUtils.isEmpty(userJob) ? "\n" + userJob.toLowerCase() : "";
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(createdAt.getTime(), System.currentTimeMillis(),
            DateUtils.SECOND_IN_MILLIS).toString().toLowerCase();

    return TextUtils.concat(poster, job, "\n", timeAgo);
}

From source file:com.waz.zclient.controllers.notifications.NotificationsController.java

@TargetApi(21)
private SpannableString getMessageSpannable(String header, String body) {
    SpannableString messageSpannable = new SpannableString(header + body);
    final int textAppearance;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textAppearance = android.R.style.TextAppearance_Material_Notification_Title;
    } else {/*from   www  .  ja va2 s .  co  m*/
        textAppearance = android.R.style.TextAppearance_StatusBar_EventContent_Title;
    }
    final TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(context, textAppearance);
    messageSpannable.setSpan(new ForegroundColorSpan(textAppearanceSpan.getTextColor().getDefaultColor()), 0,
            header.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return messageSpannable;
}

From source file:org.navitproject.navit.Navit.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_ALL: {
        if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            // ok, we got permissions
        } else {// w w  w .  j ava  2 s  . c o  m
            AlertDialog.Builder infobox = new AlertDialog.Builder(this);
            infobox.setTitle(getString(R.string.permissions_info_box_title)); // TRANS
            infobox.setCancelable(false);
            final TextView message = new TextView(this);
            message.setFadingEdgeLength(20);
            message.setVerticalFadingEdgeEnabled(true);
            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
            message.setLayoutParams(rlp);
            final SpannableString s = new SpannableString(getString(R.string.permissions_not_granted)); // TRANS
            message.setText(s);
            message.setMovementMethod(LinkMovementMethod.getInstance());
            infobox.setView(message);
            // TRANS
            infobox.setPositiveButton(getString(R.string.initial_info_box_OK),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            exit();
                        }
                    });
            infobox.show();
        }
        return;
    }
    }
}

From source file:hku.fyp14017.blencode.ui.fragment.ScriptFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    String completeTitle;/*from   w  w w .j a v  a  2  s. c  o m*/
    switch ((Integer) actionMode.getTag()) {
    case ACTION_MODE_COPY:
        completeTitle = getResources().getQuantityString(
                hku.fyp14017.blencode.R.plurals.number_of_bricks_to_copy, numberOfSelectedItems,
                numberOfSelectedItems);
        break;
    case ACTION_MODE_DELETE:
        completeTitle = getResources().getQuantityString(
                hku.fyp14017.blencode.R.plurals.number_of_bricks_to_delete, numberOfSelectedItems,
                numberOfSelectedItems);
        break;
    default:
        throw new IllegalArgumentException("Wrong or unhandled tag in ActionMode.");
    }

    int indexOfNumber = completeTitle.indexOf(' ') + 1;
    Spannable completeSpannedTitle = new SpannableString(completeTitle);
    completeSpannedTitle.setSpan(
            new ForegroundColorSpan(
                    getResources().getColor(hku.fyp14017.blencode.R.color.actionbar_title_color)),
            indexOfNumber, indexOfNumber + String.valueOf(numberOfSelectedItems).length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    actionMode.setTitle(completeSpannedTitle);
}

From source file:cmput301.f13t01.elasticsearch.ESClient.java

private void postImageData(String data, HttpPost httpPost) throws IllegalStateException, IOException {

    StringEntity stringentity = null;/*from   ww  w .  j ava2 s. c  om*/
    try {
        Text holder = new Text(new SpannableString(data));
        // Log.d("PUBLISH", "holder: " + holder.getContent());
        String test = gson.toJson(holder);
        // Log.d("PUBLISH", "gson: " + test);
        Log.d("PUBLISH", "size: " + test.length());
        String content = test;
        Log.d("PUBLISH", "holder size: " + content.length());
        // Log.d("PUBLISH", "Last bit: " +
        // content.subSequence(content.length()-128, content.length()));

        stringentity = new StringEntity(test);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    httpPost.setHeader("Accept", "application/json");

    httpPost.setEntity(stringentity);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpPost);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Log.d("PUBLISH", "Made it past execute");

    String status = response.getStatusLine().toString();
    System.out.println(status);
    HttpEntity entity = response.getEntity();
    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
    String output;
    System.err.println("Output from Server -> ");
    while ((output = br.readLine()) != null) {
        System.err.println(output);
    }

    try {
        entity.consumeContent();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return;
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service_test.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);/*w  w w . ja  v  a2s .  c  om*/
    Utility driver = new Utility(getActivity());

    if (isShowOneKey && driver.getAllDriverAccountInfo().isEmpty())
        item.setVisible(true);
    else
        item.setVisible(false);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    super.onCreateOptionsMenu(menu, inflater);
}