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:com.ymt.demo1.main.sign.SignUpFragment.java

/**
 * ???//from  ww  w  .j ava2s.  c o  m
 * ?????????
 */
protected void initView(View view) {
    /*
    
     */
    //?
    final EditText phoneTxt = (EditText) view.findViewById(R.id.input_phone_num);
    final EditText accountTxt = (EditText) view.findViewById(R.id.input_account);
    final EditText pswTxt = (EditText) view.findViewById(R.id.input_psw);
    final EditText rePswTxt = (EditText) view.findViewById(R.id.re_input_psw);
    final TextView licenseTxt = (TextView) view.findViewById(R.id.licence_txt);
    /*???? ??
     */
    final TextView getCheckNums = (TextView) view.findViewById(R.id.get_check_nums);
    final EditText inputCheckNums = (EditText) view.findViewById(R.id.input_check_nums);
    getCheckNums.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //todo ????

        }
    });

    /**
     *  todo spannableString 
     *   ?
     */
    SpannableString spannableString = new SpannableString(getString(R.string.license));
    ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.material_blue_grey_800));
    spannableString.setSpan(span, 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    licenseTxt.setText(spannableString);
    //switch(??)
    myCheckView = (MyCheckView) view.findViewById(R.id.switch_liscense);
    //
    Button signUpBtn = (Button) view.findViewById(R.id.do_sign_btn);
    signUpBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //
            String phoneNum = phoneTxt.getText().toString();
            String account = accountTxt.getText().toString();
            String psw = pswTxt.getText().toString();
            String rePsw = rePswTxt.getText().toString();
            //??
            String checkNums = inputCheckNums.getText().toString();
            //todo if(){}else{} ??

            if (!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(account) && !TextUtils.isEmpty(psw)
                    && psw.equals(rePsw)) {
                //?
                if (myCheckView.isChecked()) {
                    queue.add(signUpRequest(account, psw, phoneNum, NORMAL_USER));
                } else {
                    Toast.makeText(getActivity(), "?????",
                            Toast.LENGTH_SHORT).show();
                }

            } else if (TextUtils.isEmpty(phoneNum)) {
                //???
                Toast.makeText(getActivity(), "???", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(account)) {
                //???
                Toast.makeText(getActivity(), "???", Toast.LENGTH_SHORT).show();
            } else {
                //???
                Toast.makeText(getActivity(), "???", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    LinearLayout licence = (LinearLayout) view.findViewById(R.id.liscense_layout);
    licence.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myCheckView.callOnClick();
        }
    });
}

From source file:eltos.simpledialogfragments.FlatFragmentActivity.java

/**
 * Let the hosting fragment or activity implement this interface
 * to receive results from the dialog//  w  ww  . j  a  va 2s . c o  m
 *
 * @param dialogTag the tag passed to {@link SimpleDialog#show}
 * @param which result type, one of {@link #BUTTON_POSITIVE}, {@link #BUTTON_NEGATIVE},
 *              {@link #BUTTON_NEUTRAL} or {@link #CANCELED}
 * @param extras the extras passed to {@link SimpleDialog#extra(Bundle)}
 * @return true if the result was handled, false otherwise
 */
@Override
public boolean onResult(@NonNull String dialogTag, int which, @NonNull Bundle extras) {

    // handle results as usual
    if (COLOR_FRAGMENT.equals(dialogTag) && which == BUTTON_POSITIVE) {
        @ColorInt
        int color = extras.getInt(SimpleColorDialog.COLOR);

        // Sets action bar colors
        if (getSupportActionBar() != null) {
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xFF000000 | color));

            boolean dark = Color.red(color) * 0.299 + Color.green(color) * 0.587
                    + Color.blue(color) * 0.114 < 180;
            SpannableString s = new SpannableString(getSupportActionBar().getTitle());
            s.setSpan(new ForegroundColorSpan(dark ? Color.WHITE : Color.BLACK), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            getSupportActionBar().setTitle(s);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            float[] hsv = new float[3];
            Color.colorToHSV(color, hsv);
            hsv[2] *= 0.75;
            getWindow().setStatusBarColor(Color.HSVToColor(hsv));
        }

        return true;
    }
    return false;
}

From source file:com.techno.jay.codingcontests.Home.java

private void applyFontToMenuItem(MenuItem mi) {
    Typeface font = Typeface.createFromAsset(getAssets(), "ProductSans-Regular.ttf");
    SpannableString mNewTitle = new SpannableString(mi.getTitle());
    mNewTitle.setSpan(new CustomTypefaceSpan("", font), 0, mNewTitle.length(),
            Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    mi.setTitle(mNewTitle);/*from  w w w. j  av a 2 s .c  om*/
}

From source file:com.github.jobs.ui.fragment.JobDetailsFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle arguments = getArguments();// w ww.  ja  v  a 2 s. c  o m
    String jobId = arguments.getString(KEY_JOB_ID);
    mJob = new Job();
    mJob.setId(jobId);
    mJob = adapter.findFirst(mJob);
    if (mJob == null) {
        mJob = new Job();
        Toast.makeText(getActivity(), R.string.error_getting_job_info, Toast.LENGTH_LONG).show();
    }
    setHasOptionsMenu(true);

    TextView title = (TextView) getView().findViewById(R.id.title);
    title.setText(StringUtils.trim(mJob.getTitle()));

    TextView description = (TextView) getView().findViewById(R.id.description);
    String jobDescription = mJob.getDescription();
    if (jobDescription != null) {
        description.setText(Html.fromHtml(jobDescription));
        description.setMovementMethod(LinkMovementMethod.getInstance());
    }

    TextView company = (TextView) getView().findViewById(R.id.company);
    company.setText(mJob.getCompany());

    TextView companyUrl = (TextView) getView().findViewById(R.id.company_url);
    if (mJob.getCompanyUrl() == null) {
        companyUrl.setVisibility(View.GONE);
    } else {
        SpannableString content = new SpannableString(mJob.getCompanyUrl());
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        companyUrl.setText(content);
        companyUrl.setOnClickListener(this);
        companyUrl.setVisibility(View.VISIBLE);
    }

    TextView companyLocation = (TextView) getView().findViewById(R.id.company_location);
    if (mJob.getLocation() == null) {
        companyLocation.setVisibility(View.GONE);
    } else {
        companyLocation.setText(mJob.getLocation());
        companyLocation.setVisibility(View.VISIBLE);
    }

    if (!JobDetailsActivity.FULL_TIME.equalsIgnoreCase(mJob.getType())) {
        getView().findViewById(R.id.full_time).setVisibility(View.INVISIBLE);
    }

    mBackground = (ImageView) getView().findViewById(R.id.job_details_background);
    setLogoBackground();
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static SpannableString getSmallBalance(Context context, Coin balanceCoin, Fiat balanceFiat) {
    SpannableString result;/*from   ww w  . j a  va 2s . co m*/
    if (SharedPrefUtils.isBitcoinPrimaryBalance(context)) {
        result = toSmallSpannable(balanceFiat.toPlainString(), balanceFiat.getCurrencyCode());
    } else if (SharedPrefUtils.isFiatPrimaryBalance(context)) {
        String btcSymbol = SharedPrefUtils.getBitcoinScalePrefix(context);
        result = toSmallSpannable(scaleCoin(context, balanceCoin), btcSymbol);
    } else {
        Log.e(TAG, "Unknown setting for primary balance: " + SharedPrefUtils.getPrimaryBalance(context));
        result = new SpannableString("N/A");
    }
    return result;
}

From source file:com.example.textviewsample.MainActivityFragment.java

private void styleSourceCode() {
    TypefaceSpan codeSpan = new TypefaceSpan(getActivity(), "SourceCodePro-Regular");
    TypefaceSpan codeSpan2 = new TypefaceSpan(getActivity(), "SourceCodePro-Bold", Typeface.BOLD);
    ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.MAGENTA);
    ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(Color.BLUE);

    SpannableString title = new SpannableString(getString(R.string.code_sample));
    title.setSpan(codeSpan, 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    title.setSpan(codeSpan2, 19, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    title.setSpan(colorSpan, 4, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    title.setSpan(colorSpan2, 19, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    sourceCodeText.setText(title);/*from w  w  w  .ja v a 2 s  .c  o  m*/
}

From source file:com.dwdesign.tweetings.adapter.UserAutoCompleteAdapter.java

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    if (mCursorClosed)
        return;//from  w w  w.j  av a  2s .c  o  m
    super.bindView(view, context, cursor);
    if (mLookupText != null) {

        String statusText = cursor.getString(mStatusText);
        String finalUrl = statusText;
        SpannableString spannable = new SpannableString(statusText);
        final Matcher matcher = Regex.VALID_HASHTAG.matcher(spannable);
        while (matcher.find()) {
            final String url = matcherGroup(matcher, Regex.VALID_HASHTAG_GROUP_HASHTAG_FULL);
            if (url.toLowerCase().startsWith(mLookupText.toLowerCase())) {
                finalUrl = url;
                //break;
            }
        }

        final ImageView image_view = (ImageView) view.findViewById(android.R.id.icon);
        image_view.setVisibility(View.GONE);
        TextView text_view1 = (TextView) view.findViewById(android.R.id.text1);
        text_view1.setText(finalUrl);
        TextView text_view2 = (TextView) view.findViewById(android.R.id.text2);
        text_view2.setVisibility(View.GONE);
        //text_view2.setText(cursor.getString(mStatusText));

    } else {
        final ImageView image_view = (ImageView) view.findViewById(android.R.id.icon);
        image_view.setVisibility(mDisplayProfileImage ? View.VISIBLE : View.GONE);
        if (mDisplayProfileImage && mProfileImageLoader != null) {
            final String profile_image_url_string = cursor.getString(mProfileImageUrlIdx);
            mProfileImageLoader.displayProfileImage(image_view, cursor.getString(mProfileImageUrlIdx));
            if (mDisplayHiResProfileImage) {
                mProfileImageLoader.displayProfileImage(image_view,
                        getBiggerTwitterProfileImage(profile_image_url_string));
            } else {
                mProfileImageLoader.displayProfileImage(image_view, profile_image_url_string);
            }
        }
        TextView text_view1 = (TextView) view.findViewById(android.R.id.text1);
        text_view1.setText(cursor.getString(mScreenNameIdx));
        TextView text_view2 = (TextView) view.findViewById(android.R.id.text2);
        text_view2.setText(cursor.getString(mScreenNameIdx));

    }

}

From source file:com.directsiding.android.WebActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_web);

    // Le ponemos la font Signika al titulo del Action Bar
    SpannableString s = new SpannableString(getString(R.string.app_name));
    s.setSpan(new TypefaceSpan(this, LoginActivity.PATH_SIGNIKA_FONT), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Agregamos lo necesario al Action Bar
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);//w  w w .  j  a v  a2 s .c om
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // Obtenemos la url a la que el usuario va a ingresar
    String url = getIntent().getExtras().getString(LoginActivity.EXTRA_URL);

    // Obtenemos la cookie y la agregamos al webview
    Cookie sessionCookie = LoginOpActivity.cookie;
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    if (sessionCookie != null) {
        //cookieManager.removeSessionCookie();
        String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain="
                + sessionCookie.getDomain();
        cookieManager.setCookie(LoginActivity.POST_URL, cookieString);
        CookieSyncManager.getInstance().sync();
    }

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar_webView);
    webView = (WebView) findViewById(R.id.webView_ing);

    webViewConfig();
    webView.loadUrl(url);
    //webView.loadUrl("http://www.google.com");

    // guardamos el tiempo en el que se creo la actividad
    lastTimeStamp = SystemClock.elapsedRealtime();

}

From source file:com.google.android.gcm.demo.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.activity_main);
    mLogger = new Logger(this);
    mLogsUI = (TextView) findViewById(R.id.logs);
    mLoggerCallback = new BroadcastReceiver() {
        @Override// ww w .  j a  v  a  2s  .  c om
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
            case LoggingService.ACTION_CLEAR_LOGS:
                mLogsUI.setText("");
                break;
            case LoggingService.ACTION_LOG:
                StringBuilder stringBuilder = new StringBuilder();
                String newLog = intent.getStringExtra(LoggingService.EXTRA_LOG_MESSAGE);
                String oldLogs = Html.toHtml(new SpannableString(mLogsUI.getText()));
                appendFormattedLogLine(newLog, stringBuilder);
                stringBuilder.append(oldLogs);
                mLogsUI.setText(Html.fromHtml(stringBuilder.toString()));
                List<Fragment> fragments = getSupportFragmentManager().getFragments();
                for (Fragment fragment : fragments) {
                    if (fragment instanceof RefreshableFragment && fragment.isVisible()) {
                        ((RefreshableFragment) fragment).refresh();
                    }
                }
                break;
            }
        }
    };

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerView = (FrameLayout) findViewById(R.id.navigation_drawer);
    mDrawerMenu = (ListView) findViewById(R.id.navigation_drawer_menu);
    mDrawerScrim = findViewById(R.id.navigation_drawer_scrim);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    TypedArray colorPrimaryDark = getTheme().obtainStyledAttributes(new int[] { R.attr.colorPrimaryDark });
    mDrawerLayout.setStatusBarBackgroundColor(colorPrimaryDark.getColor(0, 0xFF000000));
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    colorPrimaryDark.recycle();

    ImageView drawerHeader = new ImageView(this);
    drawerHeader.setImageResource(R.drawable.drawer_gcm_logo);
    mDrawerMenu.addHeaderView(drawerHeader);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Set the drawer width accordingly with the guidelines: window_width - toolbar_height.
        toolbar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft,
                    int oldTop, int oldRight, int oldBottom) {
                if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                    return;
                }
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                float logicalDensity = metrics.density;
                int maxWidth = (int) Math.ceil(320 * logicalDensity);
                DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mDrawerView.getLayoutParams();
                int newWidth = view.getWidth() - view.getHeight();
                params.width = (newWidth > maxWidth ? maxWidth : newWidth);
                mDrawerView.setLayoutParams(params);
            }
        });
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        mDrawerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                // Set scrim height to match status bar height.
                mDrawerScrim.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                        insets.getSystemWindowInsetTop()));
                return insets;
            }
        });
    }

    int activeItemIndicator = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            ? android.R.layout.simple_list_item_activated_1
            : android.R.layout.simple_list_item_checked;

    mMainMenu = new MainMenu(this);
    mDrawerMenu.setOnItemClickListener(this);
    mDrawerMenu.setAdapter(new ArrayAdapter<>(getSupportActionBar().getThemedContext(), activeItemIndicator,
            android.R.id.text1, mMainMenu.getEntries()));

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            // The user learned how to open the drawer. Do not open it for him anymore.
            getAppPreferences().edit().putBoolean(PREF_OPEN_DRAWER_AT_STARTUP, false).apply();
            super.onDrawerOpened(drawerView);
        }
    };

    boolean activityResumed = (savedState != null);
    boolean openDrawer = getAppPreferences().getBoolean(PREF_OPEN_DRAWER_AT_STARTUP, true);
    int lastScreenId = getAppPreferences().getInt(PREF_LAST_SCREEN_ID, 0);
    selectItem(lastScreenId);
    if (!activityResumed && openDrawer) {
        mDrawerLayout.openDrawer(mDrawerView);
    }
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /*
     * Here we check if the Activity was created by the user clicking on one of our GCM
     * notifications:
     * 1. Check if the action of the intent used to launch the Activity.
     * 2. Print out any additional data sent with the notification. This is included as extras
     *  on the intent.
     */
    Intent launchIntent = getIntent();
    if ("gcm_test_app_notification_click_action".equals(launchIntent.getAction())) {
        Bundle data = launchIntent.getExtras();
        data.isEmpty(); // Force the bundle to unparcel so that toString() works
        String format = getResources().getString(R.string.notification_intent_received);
        mLogger.log(Log.INFO, String.format(format, data));
    }
}

From source file:io.vit.vitio.HomeActivity.java

public void setToolbarFormat(int pos) {
    theme.refreshTheme();//from w  ww .j  a va2s  .c o m
    if (!getSupportActionBar().isShowing()) {
        getSupportActionBar().show();
    }
    String title[] = getResources().getStringArray(R.array.drawer_list_titles);
    TypedArray colorres = theme.getToolbarColorTypedArray();
    Log.d("setTooltheme",
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("theme", "null"));
    getSupportActionBar()
            .setBackgroundDrawable(new ColorDrawable(getResources().getColor(colorres.getResourceId(pos, -1))));
    SpannableString s = new SpannableString(title[pos]);
    s.setSpan(theme.getMyThemeTypeFaceSpan(), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    getSupportActionBar().setTitle(s);
}