List of usage examples for android.text SpannableString SpannableString
public SpannableString(CharSequence source)
From source file:com.android.browser.GearsBaseDialog.java
/** * Display a button as an HTML link. Remove the background, set the * text color to R.color.dialog_link and draw an underline *//*www.j a v a 2s.co m*/ void displayAsLink(Button button) { if (button == null) { return; } CharSequence text = button.getText(); button.setBackgroundDrawable(null); int color = getResources().getColor(R.color.dialog_link); button.setTextColor(color); SpannableString str = new SpannableString(text); str.setSpan(new UnderlineSpan(), 0, str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); button.setText(str); button.setFocusable(false); }
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:com.android.purenexussettings.TinkerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tinker); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);//w w w . j av a 2 s.c om // set up some defaults boolean cLockInstalled; FRAG_ARRAY_START = getResources().getIntArray(R.array.nav_drawer_cat_nums)[0]; mTitle = mDrawerTitle = getTitle(); mPackageName = getPackageName(); LAST_SLIDE_BAR_TAB = 0; mBackPress = false; mIgnoreBack = false; mFromClick = false; mMenu = false; fullyClosed = true; openingHalf = true; // for backstack tracking fragmentStack = new Stack<>(); // check if cLock installed try { PackageInfo pi = getPackageManager().getPackageInfo(KEY_LOCK_CLOCK_PACKAGE_NAME, 0); cLockInstalled = pi.applicationInfo.enabled; } catch (PackageManager.NameNotFoundException e) { cLockInstalled = false; } // load slide menu items - titles and frag names navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); navMenuFrags = getResources().getStringArray(R.array.nav_drawer_fragments); // nav drawer icons from resources TypedArray navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavView = (NavigationView) findViewById(R.id.slidermenu); // create navigationview items Menu menu = mNavView.getMenu(); // pulled in crap menu in xml, need to clear it first menu.clear(); // pull in category names and numbers in each String[] navMenuCats = getResources().getStringArray(R.array.nav_drawer_cats); int[] navMenuCatCounts = getResources().getIntArray(R.array.nav_drawer_cat_nums); // set up some counters int j = 0; int total = 0; SubMenu submenu = null; // go through the total possible menu list for (int i = 0; i < navMenuTitles.length; i++) { // when the count equals a threshold value, increment/sum and add submenu if (i == (total + navMenuCatCounts[j])) { total += navMenuCatCounts[j]; // format submenu headings SpannableString strcat = new SpannableString(navMenuCats[j]); strcat.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.alphawhite)), 0, strcat.length(), 0); strcat.setSpan(new RelativeSizeSpan(0.85f), 0, strcat.length(), 0); strcat.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, strcat.length(), 0); // is the 10 * (j + 1) bit needed...? Maybe not... meh submenu = menu.addSubMenu((j + 1), 10 * (j + 1), 10 * (j + 1), strcat); j++; } // assuming all are skipped before first submenu, only add menu items if total <> 0 if (total > 0) { // format menu item title SpannableString stritem = new SpannableString(navMenuTitles[i]); stritem.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.alphawhite)), 0, stritem.length(), 0); // group id is j, i is item id and order..., then title - includes logic for conditional entries if (cLockInstalled || !(navMenuTitles[i].equals("cLock"))) { // an attempt to add icon if included... if (navMenuIcons.getResourceId(i, -1) != -1) { submenu.add(j, i, i, stritem).setIcon(navMenuIcons.getResourceId(i, -1)); } else { submenu.add(j, i, i, stritem); } } } } // remove icon tint from NavView mNavView.setItemIconTintList(null); mNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem item) { // check for external app launching navdrawer items if (navMenuTitles[item.getItemId()].equals("cLock")) { mIgnore = true; mDrawerLayout.closeDrawer(mNavView); launchcLock(); } // if nothing was caught in the above, do the usual prep to show frag stuff if (!mIgnore) { mItemPosition = item.getItemId(); mFromClick = true; setTitle(navMenuTitles[mItemPosition]); removeCurrent(); mDrawerLayout.closeDrawer(mNavView); } return true; } }); // Recycle the typed array navMenuIcons.recycle(); // enabling action bar app icon and behaving it as toggle button getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, //nav menu toggle icon R.string.app_name, // nav drawer open - description for accessibility R.string.app_name // nav drawer close - description for accessibility ) { @Override public void onDrawerClosed(View view) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mNavView); getSupportActionBar().setTitle(mTitle); // calling onPrepareOptionsMenu() to show action bar icons openingHalf = true; invalidateOptionsMenu(); // now that the drawer animation is done - load fragment if (mIgnore || !mFromClick) { mIgnore = false; } else { displayView(mItemPosition); } } @Override public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); // calling onPrepareOptionsMenu() to hide action bar icons openingHalf = false; invalidateOptionsMenu(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); fullyClosed = (slideOffset == 0.0f); if (slideOffset < 0.5f && !openingHalf) { openingHalf = true; invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } else if (slideOffset > 0.5f && openingHalf) { openingHalf = false; invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } } }; mDrawerLayout.setDrawerListener(mDrawerToggle); fragmentManager = getFragmentManager(); if (savedInstanceState == null) { // on first time display view for first nav item displayView(mItemPosition = getIntent().getIntExtra(EXTRA_START_FRAGMENT, 0)); } }
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 ww w.j av a 2 s . co m 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:org.akvo.rsr.up.UpdateEditorActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUser = SettingsUtil.getAuthUser(this); nextLocalId = SettingsUtil.ReadInt(this, ConstantUtil.LOCAL_ID_KEY, -1); // find which update we are editing // null means create a new one Bundle extras = getIntent().getExtras(); projectId = extras != null ? extras.getString(ConstantUtil.PROJECT_ID_KEY) : null; if (projectId == null) { DialogUtil.errorAlert(this, R.string.noproj_dialog_title, R.string.noproj_dialog_msg); }//from w ww . j a v a 2s . c om updateId = extras != null ? extras.getString(ConstantUtil.UPDATE_ID_KEY) : null; if (updateId == null) { updateId = savedInstanceState != null ? savedInstanceState.getString(ConstantUtil.UPDATE_ID_KEY) : null; } //Limit what we can write InputFilter postFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { boolean keepOriginal = true; StringBuilder sb = new StringBuilder(end - start); for (int i = start; i < end; i++) { char c = source.charAt(i); if (isCharAllowed(c)) // put your condition here sb.append(c); else keepOriginal = false; } if (keepOriginal) return null; else { if (source instanceof Spanned) { SpannableString sp = new SpannableString(sb); TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0); return sp; } else { return sb; } } } private boolean isCharAllowed(char c) { // return !Character.isSurrogate(c); //From API 19 return !(c >= 0xD800 && c <= 0xDFFF); } }; // get the look setContentView(R.layout.activity_update_editor); // find the fields progressGroup = findViewById(R.id.sendprogress_group); uploadProgress = (ProgressBar) findViewById(R.id.sendProgressBar); projTitleLabel = (TextView) findViewById(R.id.projupd_edit_proj_title); projupdTitleCount = (TextView) findViewById(R.id.projupd_edit_titlecount); projupdTitleCount.setText(Integer.toString(TITLE_LENGTH)); projupdTitleText = (EditText) findViewById(R.id.projupd_edit_title); projupdTitleText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(TITLE_LENGTH), postFilter }); projupdTitleText.addTextChangedListener(new TextWatcher() { //Show count of remaining characters public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { projupdTitleCount.setText(String.valueOf(TITLE_LENGTH - s.length())); } public void afterTextChanged(Editable s) { } }); projupdDescriptionText = (EditText) findViewById(R.id.projupd_edit_description); projupdDescriptionText.setFilters(new InputFilter[] { postFilter }); projupdImage = (ImageView) findViewById(R.id.image_update_detail); photoAndToolsGroup = findViewById(R.id.image_with_tools); photoAddGroup = findViewById(R.id.photo_buttons); photoCaptionText = (EditText) findViewById(R.id.projupd_edit_photo_caption); photoCaptionText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(75), postFilter }); photoCreditText = (EditText) findViewById(R.id.projupd_edit_photo_credit); photoCreditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(25), postFilter }); positionGroup = findViewById(R.id.position_group); latField = (TextView) findViewById(R.id.latitude); lonField = (TextView) findViewById(R.id.longitude); eleField = (TextView) findViewById(R.id.elevation); accuracyField = (TextView) findViewById(R.id.gps_accuracy); searchingIndicator = (TextView) findViewById(R.id.gps_searching); gpsProgress = (ProgressBar) findViewById(R.id.progress_gps); // Activate buttons btnSubmit = (Button) findViewById(R.id.btn_send_update); btnSubmit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { sendUpdate(); } }); btnDraft = (Button) findViewById(R.id.btn_save_draft); btnDraft.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { saveAsDraft(true); } }); btnTakePhoto = (Button) findViewById(R.id.btn_take_photo); btnTakePhoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // generate unique filename captureFilename = FileUtil.getExternalPhotoDir(UpdateEditorActivity.this) + File.separator + "capture" + System.nanoTime() + ".jpg"; takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(captureFilename))); startActivityForResult(takePictureIntent, photoRequest); } }); btnAttachPhoto = (Button) findViewById(R.id.btn_attach_photo); btnAttachPhoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, photoPick); } }); btnDelPhoto = (Button) findViewById(R.id.btn_delete_photo); btnDelPhoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Forget image update.setThumbnailFilename(null); // TODO: delete image file if it was taken through this app? // Hide photo w tools showPhoto(false); } }); btnRotRightPhoto = (Button) findViewById(R.id.btn_rotate_photo_r); btnRotRightPhoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Rotate image right rotatePhoto(true); } }); btnGpsGeo = (Button) findViewById(R.id.btn_gps_position); btnGpsGeo.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onGetGPSClick(view); } }); btnPhotoGeo = (Button) findViewById(R.id.btn_photo_position); btnPhotoGeo.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onGetPhotoLocationClick(view); } }); dba = new RsrDbAdapter(this); dba.open(); Project project = dba.findProject(projectId); projTitleLabel.setText(project.getTitle()); if (updateId == null) { // create new update = new Update(); update.setUuid(UUID.randomUUID().toString()); // should do sth // better, especially // if MAC address is // avaliable /* * WifiManager wifiManager = (WifiManager) * getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo = * wifiManager.getConnectionInfo(); String macAddress = * wInfo.getMacAddress(); if (macAddress == null) txt_View.append( * "MAC Address : " + macAddress + "\n" ); else txt_View.append( * "MAC Address : " + macAddress + "\n" ); } */ update.setUserId(mUser.getId()); update.setDate(new Date()); editable = true; } else { update = dba.findUpdate(updateId); if (update == null) { DialogUtil.errorAlert(this, R.string.noupd_dialog_title, R.string.noupd2_dialog_msg); } else { // populate fields editable = update.getDraft(); // This should always be true with // the current UI flow - we go to // UpdateDetailActivity if it is sent if (update.getTitle().equals(TITLE_PLACEHOLDER)) { projupdTitleText.setText(""); //placeholder is just to satisfy db } else { projupdTitleText.setText(update.getTitle()); } projupdDescriptionText.setText(update.getText()); photoCaptionText.setText(update.getPhotoCaption()); photoCreditText.setText(update.getPhotoCredit()); latField.setText(update.getLatitude()); lonField.setText(update.getLongitude()); eleField.setText(update.getElevation()); if (update.validLatLon()) { positionGroup.setVisibility(View.VISIBLE); } // show preexisting image if (update.getThumbnailFilename() != null) { // btnTakePhoto.setText(R.string.btncaption_rephoto); ThumbnailUtil.setPhotoFile(projupdImage, update.getThumbnailUrl(), update.getThumbnailFilename(), null, null, false); photoLocation = FileUtil.exifLocation(update.getThumbnailFilename()); showPhoto(true); } } } // register a listener for a completion and progress intents broadRec = new ResponseReceiver(); IntentFilter f = new IntentFilter(ConstantUtil.UPDATES_SENT_ACTION); f.addAction(ConstantUtil.UPDATES_SENDPROGRESS_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(broadRec, f); enableChanges(editable); btnDraft.setVisibility(editable ? View.VISIBLE : View.GONE); btnSubmit.setVisibility(editable ? View.VISIBLE : View.GONE); // btnTakePhoto.setVisibility(editable?View.VISIBLE:View.GONE); // Show the Up button in the action bar. // setupActionBar(); }
From source file:com.securecomcode.text.contacts.ContactSelectionListAdapter.java
@Override public void bindView(View view, Context context, Cursor cursor) { final DataHolder contactData = (DataHolder) view.getTag(R.id.contact_info_tag); final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder_tag); if (holder == null) { Log.w(TAG, "ViewHolder was null. This should not happen."); return;// w w w . j av a 2s . c om } if (contactData == null) { Log.w(TAG, "DataHolder was null. This should not happen."); return; } if (ID_COLUMN < 0) { populateColumnIndices(cursor); } contactData.type = cursor.getInt(TYPE_COLUMN); contactData.name = cursor.getString(NAME_COLUMN); contactData.number = cursor.getString(NUMBER_COLUMN); contactData.numberType = cursor.getInt(NUMBER_TYPE_COLUMN); contactData.label = cursor.getString(LABEL_COLUMN); contactData.id = cursor.getLong(ID_COLUMN); if (contactData.type != ContactsDatabase.PUSH_TYPE) { holder.name.setTextColor(drawables.getColor(1, 0xff000000)); holder.number.setTextColor(drawables.getColor(1, 0xff000000)); } else { holder.name.setTextColor(drawables.getColor(0, 0xa0000000)); holder.number.setTextColor(drawables.getColor(0, 0xa0000000)); } if (selectedContacts.containsKey(contactData.id)) { holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } holder.name.setText(contactData.name); if (contactData.number == null || contactData.number.isEmpty()) { holder.name.setEnabled(false); holder.number.setText(""); } else if (contactData.type == ContactsDatabase.PUSH_TYPE) { holder.number.setText(contactData.number); } else { final CharSequence label = ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), contactData.numberType, contactData.label); final CharSequence numberWithLabel = contactData.number + " " + label; final Spannable numberLabelSpan = new SpannableString(numberWithLabel); numberLabelSpan.setSpan(new ForegroundColorSpan(drawables.getColor(2, 0xff444444)), contactData.number.length(), numberWithLabel.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); holder.number.setText(numberLabelSpan); } holder.contactPhoto.setImageBitmap(defaultCroppedPhoto); if (contactData.id > -1) loadBitmap(contactData.number, holder.contactPhoto); }
From source file:org.freespanish.diccionario.main.MainActivity.java
@Override public void showAboutDialog() { final SpannableString spannableString = new SpannableString(getString(R.string.about_msg)); Linkify.addLinks(spannableString, Linkify.ALL); final AlertDialog aboutDialog = new AlertDialog.Builder(this).setPositiveButton(android.R.string.ok, null) .setTitle(getString(R.string.app_name) + " " + getString(R.string.app_version)) .setMessage(spannableString).create(); aboutDialog.show();//from ww w . ja va 2 s.c om ((TextView) aboutDialog.findViewById(android.R.id.message)) .setMovementMethod(LinkMovementMethod.getInstance()); }
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);//from w w w. j a v a2 s .c o m 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:org.kontalk.ui.view.ConversationListItem.java
public final void bind(Context context, final Conversation conv) { mConversation = conv;// www .j av a 2s .co m setChecked(false); Contact contact; // used for the conversation subject: either group subject or contact name String recipient = null; if (mConversation.isGroupChat()) { recipient = mConversation.getGroupSubject(); if (TextUtils.isEmpty(recipient)) recipient = context.getString(R.string.group_untitled); loadAvatar(null); } else { contact = mConversation.getContact(); if (contact != null) { recipient = contact.getDisplayName(); } if (recipient == null) { if (BuildConfig.DEBUG) { recipient = conv.getRecipient(); } else { recipient = context.getString(R.string.peer_unknown); } } loadAvatar(contact); } SpannableStringBuilder from = new SpannableStringBuilder(recipient); if (conv.getUnreadCount() > 0) from.setSpan(STYLE_BOLD, 0, from.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); // draft indicator int lastpos = from.length(); String draft = conv.getDraft(); if (draft != null) { from.append(" "); from.append(context.getResources().getString(R.string.has_draft)); from.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.text_color_draft)), lastpos, from.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } mFromView.setText(from); mDateView.setText(MessageUtils.formatTimeStampString(context, conv.getDate())); mSticky.setVisibility(conv.isSticky() ? VISIBLE : GONE); // error indicator int resId = -1; int statusId = -1; switch (conv.getStatus()) { case Messages.STATUS_SENDING: // use pending icon even for errors case Messages.STATUS_ERROR: case Messages.STATUS_PENDING: case Messages.STATUS_QUEUED: resId = R.drawable.ic_msg_pending; statusId = R.string.msg_status_sending; break; case Messages.STATUS_SENT: resId = R.drawable.ic_msg_sent; statusId = R.string.msg_status_sent; break; case Messages.STATUS_RECEIVED: resId = R.drawable.ic_msg_delivered; statusId = R.string.msg_status_delivered; break; // here we use the error icon case Messages.STATUS_NOTACCEPTED: resId = R.drawable.ic_thread_error; statusId = R.string.msg_status_notaccepted; break; case Messages.STATUS_NOTDELIVERED: resId = R.drawable.ic_msg_notdelivered; statusId = R.string.msg_status_notdelivered; break; } // no matching resource or draft - hide status icon boolean incoming = resId < 0; if (incoming || draft != null) { mErrorIndicator.setVisibility(GONE); int unread = mConversation.getUnreadCount(); if (unread > 0) { mCounterView.setText(String.valueOf(unread)); mCounterView.setVisibility(VISIBLE); } else { mCounterView.setVisibility(GONE); } } else { mCounterView.setVisibility(GONE); mErrorIndicator.setVisibility(VISIBLE); mErrorIndicator.setImageResource(resId); mErrorIndicator.setContentDescription(getResources().getString(statusId)); } CharSequence text; // last message or draft?? if (conv.getRequestStatus() == Threads.REQUEST_WAITING) { text = new SpannableString(context.getString(R.string.text_invitation_info)); ((Spannable) text).setSpan(STYLE_ITALIC, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } else { String subject = conv.getSubject(); String source = (draft != null) ? draft : subject; if (source != null) { if (GroupCommandComponent.supportsMimeType(conv.getMime()) && draft == null) { if (incoming) { // content is in a special format GroupThreadContent parsed = GroupThreadContent.parseIncoming(subject); subject = parsed.command; } text = new SpannableString( GroupCommandComponent.getTextContent(getContext(), subject, incoming)); ((Spannable) text).setSpan(STYLE_ITALIC, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } else { if (incoming && conv.isGroupChat()) { // content is in a special format GroupThreadContent parsed = GroupThreadContent.parseIncoming(subject); contact = parsed.sender != null ? Contact.findByUserId(context, parsed.sender) : null; source = parsed.command; String displayName = null; if (contact != null) displayName = contact.getDisplayName(); if (displayName == null) { if (BuildConfig.DEBUG) { displayName = conv.getRecipient(); } else { displayName = context.getString(R.string.peer_unknown); } } if (source == null) { // determine from mime type source = CompositeMessage.getSampleTextContent(conv.getMime()); } text = new SpannableString(displayName + ": " + source); ((Spannable) text).setSpan(STYLE_ITALIC, 0, displayName.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } else { text = source; } } } else if (conv.isEncrypted()) { text = context.getString(R.string.text_encrypted); } else { // determine from mime type text = CompositeMessage.getSampleTextContent(conv.getMime()); } } if (conv.getUnreadCount() > 0) { text = new SpannableString(text); ((Spannable) text).setSpan(STYLE_BOLD, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } mSubjectView.setText(text); }
From source file:com.evandroid.musica.fragment.LyricsViewFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true);//from w w w . j a v a2 s . c om setHasOptionsMenu(true); View layout = inflater.inflate(R.layout.lyrics_view, container, false); if (savedInstanceState != null) try { Lyrics l = Lyrics.fromBytes(savedInstanceState.getByteArray("lyrics")); if (l != null) this.mLyrics = l; mSearchQuery = savedInstanceState.getString("searchQuery"); mSearchFocused = savedInstanceState.getBoolean("searchFocused"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } else { Bundle args = getArguments(); if (args != null) try { Lyrics lyrics = Lyrics.fromBytes(args.getByteArray("lyrics")); this.mLyrics = lyrics; if (lyrics != null && lyrics.getText() == null && lyrics.getArtist() != null) { String artist = lyrics.getArtist(); String track = lyrics.getTrack(); String url = lyrics.getURL(); fetchLyrics(artist, track, url); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } if (layout != null) { Bundle args = savedInstanceState != null ? savedInstanceState : getArguments(); boolean screenOn = PreferenceManager.getDefaultSharedPreferences(getActivity()) .getBoolean("pref_force_screen_on", false); TextSwitcher textSwitcher = (TextSwitcher) layout.findViewById(R.id.switcher); textSwitcher.setFactory(new LyricsTextFactory(layout.getContext())); ActionMode.Callback callback = new CustomSelectionCallback(getActivity()); ((TextView) textSwitcher.getChildAt(0)).setCustomSelectionActionModeCallback(callback); ((TextView) textSwitcher.getChildAt(1)).setCustomSelectionActionModeCallback(callback); textSwitcher.setKeepScreenOn(screenOn); layout.findViewById(R.id.lrc_view).setKeepScreenOn(screenOn); TextView id3TV = (TextView) layout.findViewById(R.id.id3_tv); SpannableString text = new SpannableString(id3TV.getText()); text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0); id3TV.setText(text); final RefreshIcon refreshFab = (RefreshIcon) getActivity().findViewById(R.id.refresh_fab); refreshFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mRefreshLayout.isRefreshing()) fetchCurrentLyrics(true); } }); FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class); startActivity(settingsIntent); } }); if (args != null) refreshFab.setEnabled(args.getBoolean("refreshFabEnabled", true)); mScrollView = (NestedScrollView) layout.findViewById(R.id.scrollview); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); TypedValue primaryColor = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.colorPrimary, primaryColor, true); mRefreshLayout.setColorSchemeResources(primaryColor.resourceId, R.color.accent); float offset = getResources().getDisplayMetrics().density * 64; mRefreshLayout.setProgressViewEndTarget(true, (int) offset); mRefreshLayout.setOnRefreshListener(this); if (mLyrics == null) { if (!startEmtpy) fetchCurrentLyrics(false); } else if (mLyrics.getFlag() == Lyrics.SEARCH_ITEM) { mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); if (mLyrics.getArtist() != null) fetchLyrics(mLyrics.getArtist(), mLyrics.getTrack()); } else //Rotation, resume update(mLyrics, layout, false); } if (broadcastReceiver == null) broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { searchResultLock = false; String artist = intent.getStringExtra("artist"); String track = intent.getStringExtra("track"); if (artist != null && track != null && mRefreshLayout.isEnabled()) { startRefreshAnimation(); new ParseTask(LyricsViewFragment.this, false, true).execute(mLyrics); } } }; return layout; }