List of usage examples for android.util TypedValue COMPLEX_UNIT_SP
int COMPLEX_UNIT_SP
To view the source code for android.util TypedValue COMPLEX_UNIT_SP.
Click Source Link
From source file:com.cleverzone.zhizhi.capture.CaptureActivity.java
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) { final CharSequence displayContents = resultHandler.getDisplayContents(); // if (copyToClipboard && !resultHandler.areContentsSecure()) { // ClipboardInterface.setText(displayContents, this); // }//from w ww. j a v a 2s .c o m SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) { // resultHandler.handleButtonPress(resultHandler.getDefaultButtonID()); // return; // } statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view); if (barcode == null) { barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(R.id.format_text_view); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = (TextView) findViewById(R.id.type_text_view); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); TextView timeTextView = (TextView) findViewById(R.id.time_text_view); timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp()))); TextView metaTextView = (TextView) findViewById(R.id.meta_text_view); View metaTextViewLabel = findViewById(R.id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } final TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); final String baseUrl = "http://qrk.kuaipai.cn/loganal/base/scan/show-json-advert.action?code="; new Thread(new Runnable() { @Override public void run() { HttpGet get = new HttpGet(baseUrl + displayContents); Log.e(TAG, "full url = " + baseUrl + displayContents); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); String json = EntityUtils.toString(response.getEntity(), "UTF-8"); JSONObject jsonObject = new JSONObject(json); NetScanResult result = new NetScanResult(); result.name = jsonObject.getString("name"); result.url = jsonObject.getString("img"); Message message = new Message(); message.obj = result; message.what = 1; mNetHandler.sendMessage(message); } catch (Exception e) { mNetHandler.sendEmptyMessage(-1); e.printStackTrace(); } } }).start(); // contentsTextView.setText(displayContents); int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view); supplementTextView.setText(""); supplementTextView.setOnClickListener(null); // if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( // PreferencesActivity.KEY_SUPPLEMENTAL, true)) { // SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, // resultHandler.getResult(), // historyManager, // this); // } int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } }
From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) { statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view); if (barcode == null) { barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.qr_scan)); } else {/*from w w w .ja v a2 s . co m*/ barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(R.id.format_text_view); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = (TextView) findViewById(R.id.type_text_view); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); String formattedTime = formatter.format(new Date(rawResult.getTimestamp())); TextView timeTextView = (TextView) findViewById(R.id.time_text_view); timeTextView.setText(formattedTime); TextView metaTextView = (TextView) findViewById(R.id.meta_text_view); View metaTextViewLabel = findViewById(R.id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); CharSequence displayContents = resultHandler.getDisplayContents(); contentsTextView.setText(displayContents); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view); supplementTextView.setText(""); supplementTextView.setOnClickListener(null); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PreferencesActivity.KEY_SUPPLEMENTAL, true)) { SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, resultHandler.getResult(), historyManager, this); } int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); if (displayContents != null) { clipboard.setText(displayContents); } } }
From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java
public static int spToPixels(Context context, int spValue) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics()); }
From source file:com.gelakinetic.mtgfam.fragments.CardViewFragment.java
/** * This will fill the UI elements with information from the database * It also saves information for AsyncTasks to use later and manages the transform/flip button * * @param id the ID of the the card to be displayed * @return true if the UI was filled in, false otherwise *///from ww w .j a v a 2s . c o m public void setInfoFromID(final long id) { /* If the views are null, don't attempt to fill them in */ if (mSetTextView == null) { return; } ImageGetter imgGetter = ImageGetterHelper.GlyphGetter(getActivity()); SQLiteDatabase database = DatabaseManager.getInstance(getActivity(), false).openDatabase(false); Cursor cCardById; try { cCardById = CardDbAdapter.fetchCards(new long[] { id }, null, database); } catch (FamiliarDbException e) { handleFamiliarDbException(true); DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); return; } /* http://magiccards.info/scans/en/mt/55.jpg */ mCardName = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME)); mCardCMC = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_CMC)); mSetCode = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)); /* Start building a description */ addToDescription(getString(R.string.search_name), mCardName); try { mSetName = CardDbAdapter.getSetNameFromCode(mSetCode, database); addToDescription(getString(R.string.search_set), mSetName); } catch (FamiliarDbException e) { /* no set for you */ } try { mMagicCardsInfoSetCode = CardDbAdapter .getCodeMtgi(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)), database); } catch (FamiliarDbException e) { handleFamiliarDbException(true); DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); return; } mCardNumber = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NUMBER)); switch ((char) cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_RARITY))) { case 'C': case 'c': mSetTextView .setTextColor(ContextCompat.getColor(getContext(), getResourceIdFromAttr(R.attr.color_common))); addToDescription(getString(R.string.search_rarity), getString(R.string.search_Common)); break; case 'U': case 'u': mSetTextView.setTextColor( ContextCompat.getColor(getContext(), getResourceIdFromAttr(R.attr.color_uncommon))); addToDescription(getString(R.string.search_rarity), getString(R.string.search_Uncommon)); break; case 'R': case 'r': mSetTextView .setTextColor(ContextCompat.getColor(getContext(), getResourceIdFromAttr(R.attr.color_rare))); addToDescription(getString(R.string.search_rarity), getString(R.string.search_Rare)); break; case 'M': case 'm': mSetTextView .setTextColor(ContextCompat.getColor(getContext(), getResourceIdFromAttr(R.attr.color_mythic))); addToDescription(getString(R.string.search_rarity), getString(R.string.search_Mythic)); break; case 'T': case 't': mSetTextView.setTextColor( ContextCompat.getColor(getContext(), getResourceIdFromAttr(R.attr.color_timeshifted))); addToDescription(getString(R.string.search_rarity), getString(R.string.search_Timeshifted)); break; } String sCost = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_MANACOST)); addToDescription(getString(R.string.search_mana_cost), sCost); CharSequence csCost = ImageGetterHelper.formatStringWithGlyphs(sCost, imgGetter); mCostTextView.setText(csCost); String sAbility = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ABILITY)); addToDescription(getString(R.string.search_text), sAbility); CharSequence csAbility = ImageGetterHelper.formatStringWithGlyphs(sAbility, imgGetter); mAbilityTextView.setText(csAbility); mAbilityTextView.setMovementMethod(LinkMovementMethod.getInstance()); String sFlavor = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_FLAVOR)); addToDescription(getString(R.string.search_flavor_text), sFlavor); CharSequence csFlavor = ImageGetterHelper.formatStringWithGlyphs(sFlavor, imgGetter); mFlavorTextView.setText(csFlavor); mNameTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME))); mCardType = CardDbAdapter.getTypeLine(cCardById); mTypeTextView.setText(mCardType); mSetTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET))); mArtistTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST))); String numberAndRarity = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NUMBER)) + " (" + (char) cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_RARITY)) + ")"; mNumberTextView.setText(numberAndRarity); addToDescription(getString(R.string.search_type), CardDbAdapter.getTypeLine(cCardById)); addToDescription(getString(R.string.search_artist), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST))); addToDescription(getString(R.string.search_collectors_number), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NUMBER))); int loyalty = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_LOYALTY)); float p = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_POWER)); float t = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_TOUGHNESS)); if (loyalty != CardDbAdapter.NO_ONE_CARES) { if (loyalty == CardDbAdapter.X) { mPowTouTextView.setText("X"); } else { mPowTouTextView.setText(Integer.valueOf(loyalty).toString()); } } else if (p != CardDbAdapter.NO_ONE_CARES && t != CardDbAdapter.NO_ONE_CARES) { String powTouStr = ""; if (p == CardDbAdapter.STAR) powTouStr += "*"; else if (p == CardDbAdapter.ONE_PLUS_STAR) powTouStr += "1+*"; else if (p == CardDbAdapter.TWO_PLUS_STAR) powTouStr += "2+*"; else if (p == CardDbAdapter.SEVEN_MINUS_STAR) powTouStr += "7-*"; else if (p == CardDbAdapter.STAR_SQUARED) powTouStr += "*^2"; else if (p == CardDbAdapter.X) powTouStr += "X"; else { if (p == (int) p) { powTouStr += (int) p; } else { powTouStr += p; } } powTouStr += "/"; if (t == CardDbAdapter.STAR) powTouStr += "*"; else if (t == CardDbAdapter.ONE_PLUS_STAR) powTouStr += "1+*"; else if (t == CardDbAdapter.TWO_PLUS_STAR) powTouStr += "2+*"; else if (t == CardDbAdapter.SEVEN_MINUS_STAR) powTouStr += "7-*"; else if (t == CardDbAdapter.STAR_SQUARED) powTouStr += "*^2"; else if (t == CardDbAdapter.X) powTouStr += "X"; else { if (t == (int) t) { powTouStr += (int) t; } else { powTouStr += t; } } addToDescription(getString(R.string.search_power), powTouStr); mPowTouTextView.setText(powTouStr); } else { mPowTouTextView.setText(""); } boolean isMultiCard = false; switch (CardDbAdapter.isMultiCard(mCardNumber, cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)))) { case NOPE: isMultiCard = false; mTransformButton.setVisibility(View.GONE); mTransformButtonDivider.setVisibility(View.GONE); break; case TRANSFORM: isMultiCard = true; mTransformButton.setVisibility(View.VISIBLE); mTransformButtonDivider.setVisibility(View.VISIBLE); mTransformButton.setText(R.string.card_view_transform); break; case FUSE: isMultiCard = true; mTransformButton.setVisibility(View.VISIBLE); mTransformButtonDivider.setVisibility(View.VISIBLE); mTransformButton.setText(R.string.card_view_fuse); break; case SPLIT: isMultiCard = true; mTransformButton.setVisibility(View.VISIBLE); mTransformButtonDivider.setVisibility(View.VISIBLE); mTransformButton.setText(R.string.card_view_other_half); break; } if (isMultiCard) { if (mCardNumber.contains("a")) { mTransformCardNumber = mCardNumber.replace("a", "b"); } else if (mCardNumber.contains("b")) { mTransformCardNumber = mCardNumber.replace("b", "a"); } try { mTransformId = CardDbAdapter.getIdFromSetAndNumber(mSetCode, mTransformCardNumber, database); } catch (FamiliarDbException e) { handleFamiliarDbException(true); DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); return; } if (mTransformId == -1) { mTransformButton.setVisibility(View.GONE); mTransformButtonDivider.setVisibility(View.GONE); } else { mTransformButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { releaseImageResources(true); mCardNumber = mTransformCardNumber; setInfoFromID(mTransformId); } }); } } mMultiverseId = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_MULTIVERSEID)); /* Do we load the image immediately to the main page, or do it in a dialog later? */ if (mActivity.mPreferenceAdapter.getPicFirst()) { mImageScrollView.setVisibility(View.VISIBLE); mTextScrollView.setVisibility(View.GONE); mActivity.setLoading(); if (mAsyncTask != null) { mAsyncTask.cancel(true); } mAsyncTask = new FetchPictureTask(); ((FetchPictureTask) mAsyncTask).execute(MAIN_PAGE); } else { mImageScrollView.setVisibility(View.GONE); mTextScrollView.setVisibility(View.VISIBLE); } /* Figure out how large the color indicator should be. Medium text is 18sp, with a border its 22sp */ int dimension = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 22, getResources().getDisplayMetrics()); mColorIndicatorLayout.removeAllViews(); ColorIndicatorView civ = new ColorIndicatorView(this.getActivity(), dimension, dimension / 15, cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_COLOR)), sCost); if (civ.shouldInidcatorBeShown()) { mColorIndicatorLayout.setVisibility(View.VISIBLE); mColorIndicatorLayout.addView(civ); } else { mColorIndicatorLayout.setVisibility(View.GONE); } String allLanguageKeys[][] = { { Language.Chinese_Traditional, CardDbAdapter.KEY_NAME_CHINESE_TRADITIONAL, CardDbAdapter.KEY_MULTIVERSEID_CHINESE_TRADITIONAL }, { Language.Chinese_Simplified, CardDbAdapter.KEY_NAME_CHINESE_SIMPLIFIED, CardDbAdapter.KEY_MULTIVERSEID_CHINESE_SIMPLIFIED }, { Language.French, CardDbAdapter.KEY_NAME_FRENCH, CardDbAdapter.KEY_MULTIVERSEID_FRENCH }, { Language.German, CardDbAdapter.KEY_NAME_GERMAN, CardDbAdapter.KEY_MULTIVERSEID_GERMAN }, { Language.Italian, CardDbAdapter.KEY_NAME_ITALIAN, CardDbAdapter.KEY_MULTIVERSEID_ITALIAN }, { Language.Japanese, CardDbAdapter.KEY_NAME_JAPANESE, CardDbAdapter.KEY_MULTIVERSEID_JAPANESE }, { Language.Portuguese_Brazil, CardDbAdapter.KEY_NAME_PORTUGUESE_BRAZIL, CardDbAdapter.KEY_MULTIVERSEID_PORTUGUESE_BRAZIL }, { Language.Russian, CardDbAdapter.KEY_NAME_RUSSIAN, CardDbAdapter.KEY_MULTIVERSEID_RUSSIAN }, { Language.Spanish, CardDbAdapter.KEY_NAME_SPANISH, CardDbAdapter.KEY_MULTIVERSEID_SPANISH }, { Language.Korean, CardDbAdapter.KEY_NAME_KOREAN, CardDbAdapter.KEY_MULTIVERSEID_KOREAN } }; // Clear the translations first mTranslatedNames.clear(); // Add English Card.ForeignPrinting englishPrinting = new Card.ForeignPrinting(); englishPrinting.mLanguageCode = Language.English; englishPrinting.mName = mCardName; englishPrinting.mMultiverseId = mMultiverseId; mTranslatedNames.add(englishPrinting); // Add all the others for (String lang[] : allLanguageKeys) { Card.ForeignPrinting fp = new Card.ForeignPrinting(); fp.mLanguageCode = lang[0]; fp.mName = cCardById.getString(cCardById.getColumnIndex(lang[1])); fp.mMultiverseId = cCardById.getInt(cCardById.getColumnIndex(lang[2])); if (fp.mName != null && !fp.mName.isEmpty()) { mTranslatedNames.add(fp); } } cCardById.close(); /* Find the other sets this card is in ahead of time, so that it can be remove from the menu if there is only one set */ Cursor cCardByName; try { cCardByName = CardDbAdapter.fetchCardByName(mCardName, new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_SET, CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID, CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_NUMBER }, false, database); } catch (FamiliarDbException e) { handleFamiliarDbException(true); DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); return; } mPrintings = new LinkedHashSet<>(); mCardIds = new LinkedHashSet<>(); while (!cCardByName.isAfterLast()) { try { String number = cCardByName.getString(cCardByName.getColumnIndex(CardDbAdapter.KEY_NUMBER)); if (!(number == null || number.length() == 0)) { number = " (" + number + ")"; } else { number = ""; } if (mPrintings.add(CardDbAdapter.getSetNameFromCode( cCardByName.getString(cCardByName.getColumnIndex(CardDbAdapter.KEY_SET)), database) + number)) { mCardIds.add(cCardByName.getLong(cCardByName.getColumnIndex(CardDbAdapter.KEY_ID))); } } catch (FamiliarDbException e) { handleFamiliarDbException(true); DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); return; } cCardByName.moveToNext(); } cCardByName.close(); /* If it exists in only one set, remove the button from the menu */ if (mPrintings.size() == 1) { mActivity.supportInvalidateOptionsMenu(); } DatabaseManager.getInstance(getActivity(), false).closeDatabase(false); if (mShouldReportView) { reportAppIndexViewIfAble(); } }
From source file:terse.a1.TerseActivity.java
private void viewPath9display(String path, LayoutParams widgetParams) { String explain;//from w w w .j ava 2s.c o m if (terp_error != null) { explain = "terp_error = " + terp_error; } else { try { terp.say("Sending to terp: %s", path); final Dict d = terp.handleUrl(path, taQuery); explain = "DEFAULT EXPLANATION:\n\n" + d.toString(); Str TYPE = d.cls.terp.newStr("type"); Str VALUE = d.cls.terp.newStr("value"); Str TITLE = d.cls.terp.newStr("title"); Str type = (Str) d.dict.get(TYPE); Ur value = d.dict.get(VALUE); Ur title = d.dict.get(TITLE); // { // double ticks = Static.floatAt(d, "ticks", -1); // double nanos = Static.floatAt(d, "nanos", -1); // Toast.makeText( // getApplicationContext(), // Static.fmt("%d ticks, %.3f secs", (long) ticks, // (double) nanos / 1e9), Toast.LENGTH_SHORT) // .show(); // } if (type.str.equals("list") && value instanceof Vec) { final ArrayList<Ur> v = ((Vec) value).vec; final ArrayList<String> labels = new ArrayList<String>(); final ArrayList<String> links = new ArrayList<String>(); for (int i = 0; i < v.size(); i++) { Ur item = v.get(i); String label = item instanceof Str ? ((Str) item).str : item.toString(); if (item instanceof Vec && ((Vec) item).vec.size() == 2) { // OLD STYLE label = ((Vec) item).vec.get(0).toString(); Matcher m = LINK_P.matcher(label); if (m.lookingAt()) { label = m.group(2) + " " + m.group(3); } label += " [" + ((Vec) item).vec.get(1).toString().length() + "]"; links.add(null); // Use old style, not links. } else { // NEW STYLE label = item.toString(); if (label.charAt(0) == '/') { String link = Terp.WHITE_PLUS.split(label, 2)[0]; links.add(link); } else { links.add(""); } } labels.add(label); } if (labels.size() != links.size()) terp.toss("lables#%d links#%d", labels.size(), links.size()); ListView listv = new ListView(this); listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels)); listv.setLayoutParams(widgetParams); listv.setTextFilterEnabled(true); listv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text // Toast.makeText(getApplicationContext(), // ((TextView) view).getText(), // Toast.LENGTH_SHORT).show(); String toast_text = ((TextView) view).getText().toString(); // if (v.get(position) instanceof Vec) { if (links.get(position) == null) { // OLD STYLE Vec pair = (Vec) v.get(position); if (pair.vec.size() == 2) { if (pair.vec.get(0) instanceof Str) { String[] words = ((Str) pair.vec.get(0)).str.split("\\|"); Log.i("TT-WORDS", terp.arrayToString(words)); toast_text += "\n\n" + Static.arrayToString(words); if (words[1].equals("link")) { Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build(); Intent intent = new Intent("android.intent.action.MAIN", uri); intent.setClass(getApplicationContext(), TerseActivity.class); startActivity(intent); } } } } else { // NEW STYLE terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position, links.get(position), labels.get(position)); if (links.get(position).length() > 0) { Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build(); Intent intent = new Intent("android.intent.action.MAIN", uri); intent.setClass(getApplicationContext(), TerseActivity.class); startActivity(intent); } } // } // Toast.makeText(getApplicationContext(), // ((TextView) view).getText(), // Toast.LENGTH_SHORT).show(); } }); setContentView(listv); return; } else if (type.str.equals("edit") && value instanceof Str) { final EditText ed = new EditText(this); ed.setText(taSaveMe == null ? value.toString() : taSaveMe); ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); ed.setLayoutParams(widgetParams); // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); ed.setTextAppearance(this, R.style.teletype); ed.setBackgroundColor(Color.BLACK); ed.setGravity(Gravity.TOP); ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); ed.setVerticalFadingEdgeEnabled(true); ed.setVerticalScrollBarEnabled(true); ed.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" // button // if ((event.getAction() == KeyEvent.ACTION_DOWN) // && // (keyCode == KeyEvent.KEYCODE_ENTER)) { // // Perform action on key press // Toast.makeText(TerseActivity.this, ed.getText(), // Toast.LENGTH_SHORT).show(); // return true; // } return false; } }); Button btn = new Button(this); btn.setText("Save"); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks String text = ed.getText().toString(); text = Parser.charSubsts(text); Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show(); String action = stringAt(d, "action"); String query = ""; String f1 = stringAt(d, "field1"); String v1 = stringAt(d, "value1"); String f2 = stringAt(d, "field2"); String v2 = stringAt(d, "value2"); f1 = (f1 == null) ? "f1null" : f1; v1 = (v1 == null) ? "v1null" : v1; f2 = (f2 == null) ? "f2null" : f2; v2 = (v2 == null) ? "v2null" : v2; startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"), stringAt(d, "field2"), stringAt(d, "value2"), "text", text); } }); LinearLayout linear = new LinearLayout(this); linear.setOrientation(LinearLayout.VERTICAL); linear.addView(btn); linear.addView(ed); setContentView(linear); return; } else if (type.str.equals("draw") && value instanceof Vec) { Vec v = ((Vec) value); DrawView dv = new DrawView(this, v.vec, d); dv.setLayoutParams(widgetParams); setContentView(dv); return; } else if (type.str.equals("live")) { Blk blk = value.mustBlk(); Blk event = Static.urAt(d, "event").asBlk(); TerseSurfView tsv = new TerseSurfView(this, blk, event); setContentView(tsv); return; } else if (type.str.equals("fnord")) { Blk blk = value.mustBlk(); Blk event = Static.urAt(d, "event").asBlk(); FnordView fnord = new FnordView(this, blk, event); setContentView(fnord); return; } else if (type.str.equals("world") && value instanceof Str) { String newWorld = value.toString(); if (Terp.WORLD_P.matcher(newWorld).matches()) { world = newWorld; resetTerp(); explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world); Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show(); } else { terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld); } // Fall thru for explainv.setText(explain). } else if (type.str.equals("text")) { explain = "<<< " + title + " >>>\n\n" + value.toString(); // Fall thru for explainv.setText(explain). } else if (type.str.equals("html")) { final WebView webview = new WebView(this); // webview.loadData(value.toString(), "text/html", null); webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // terp.say("WebView UrlLoading: url=%s", url); URI uri = URI.create("" + url); // terp.say("WebView UrlLoading: URI=%s", uri); terp.say("WebView UrlLoading: getPath=%s", uri.getPath()); terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery()); // Toast.makeText(getApplicationContext(), // uri.toASCIIString(), Toast.LENGTH_SHORT) // .show(); // webview.invalidate(); // // TextView quick = new // TextView(TerseActivity.this); // quick.setText(uri.toASCIIString()); // quick.setBackgroundColor(Color.BLACK); // quick.setTextColor(Color.WHITE); // setContentView(quick); startTerseActivity(uri.getPath(), uri.getQuery()); return true; } }); // webview.setWebChromeClient(new WebChromeClient()); webview.getSettings().setBuiltInZoomControls(true); // webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setDefaultFontSize(18); webview.getSettings().setNeedInitialFocus(true); webview.getSettings().setSupportZoom(true); webview.getSettings().setSaveFormData(true); setContentView(webview); // ScrollView scrollv = new ScrollView(this); // scrollv.addView(webview); // setContentView(scrollv); return; } else { explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls + "\n\n##############\n\n"; explain += value.toString(); // Fall thru for explainv.setText(explain). } } catch (Exception ex) { ex.printStackTrace(); explain = Static.describe(ex); } } TextView explainv = new TextView(this); explainv.setText(explain); explainv.setBackgroundColor(Color.BLACK); explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); explainv.setTextColor(Color.YELLOW); SetContentViewWithHomeButtonAndScroll(explainv); }
From source file:terse.a1.TerseActivity.java
private void postMortem(Throwable ex) { String explain = Static.describe(ex); TextView explainv = new TextView(this); explainv.setText(explain);/*w w w . ja v a 2 s .c om*/ explainv.setBackgroundColor(Color.BLACK); explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); explainv.setTextColor(Color.RED); SetContentViewWithHomeButtonAndScroll(explainv); }
From source file:edu.sfsu.cs.orange.ocr.CaptureActivity.java
/** * Displays information relating to the result of OCR, and requests a translation if necessary. * //ww w . j a v a 2 s . c o m * @param ocrResult Object representing successful OCR results * @return True if a non-null result was received for OCR */ boolean handleOcrDecode(OcrResult ocrResult) { lastResult = ocrResult; // Test whether the result is null if (ocrResult.getText() == null || ocrResult.getText().equals("")) { Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); return false; } // Turn off capture-related UI elements shutterButton.setVisibility(View.GONE); statusViewBottom.setVisibility(View.GONE); statusViewTop.setVisibility(View.GONE); cameraButtonView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView bitmapImageView = (ImageView) findViewById(R.id.image_view); lastBitmap = ocrResult.getBitmap(); if (lastBitmap == null) { bitmapImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)); } else { bitmapImageView.setImageBitmap(lastBitmap); } // Display the recognized text TextView sourceLanguageTextView = (TextView) findViewById(R.id.source_language_text_view); sourceLanguageTextView.setText(sourceLanguageReadable); TextView ocrResultTextView = (TextView) findViewById(R.id.ocr_result_text_view); ocrResultTextView.setText(ocrResult.getText()); String rawText = ocrResult.getText(); rawText.split("\n"); String[] beerNames = rawText.split("\n"); for (String beer : beerNames) { beerQuery.asyncBeerFetch(beer, aq); } ocrResultTextView.setText(aq.getText()); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - ocrResult.getText().length() / 4); ocrResultTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView translationLanguageLabelTextView = (TextView) findViewById( R.id.translation_language_label_text_view); TextView translationLanguageTextView = (TextView) findViewById(R.id.translation_language_text_view); TextView translationTextView = (TextView) findViewById(R.id.translation_text_view); translationLanguageLabelTextView.setVisibility(View.GONE); translationLanguageTextView.setVisibility(View.GONE); translationTextView.setVisibility(View.GONE); progressView.setVisibility(View.GONE); setProgressBarVisibility(false); return true; }
From source file:self.philbrown.droidQuery.$.java
/** * Interprets the CSS-style String and sets the value * @param view the view that will change. * @param key the name of the attribute/*from w w w .jav a 2s . c om*/ * @param _value the end animation value * @return the computed value */ public Number getAnimationValue(View view, String key, String _value) { Number value = null; boolean negativeValue = false; if (_value.startsWith("-")) { negativeValue = true; _value = _value.substring(1); } String[] split = (_value).split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); if (negativeValue) split[0] = String.format(Locale.US, "-%s", split[0]); if (split.length == 1) { if (split[0].contains(".")) { value = Float.valueOf(split[0]); } else { value = Integer.valueOf(split[0]); } } else { if (split.length > 2) { Log.w("droidQuery", "parsererror for key " + key); return null; } if (split[1].equalsIgnoreCase("px")) { //this is the default. Just determine if float or int if (split[0].contains(".")) { value = Float.valueOf(split[0]); } else { value = Integer.valueOf(split[0]); } } else if (split[1].equalsIgnoreCase("dip") || split[1].equalsIgnoreCase("dp")) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Float.parseFloat(split[0]), context.getResources().getDisplayMetrics()); if (split[0].contains(".")) { value = px; } else { value = (int) px; } } else if (split[1].equalsIgnoreCase("in")) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, Float.parseFloat(split[0]), context.getResources().getDisplayMetrics()); if (split[0].contains(".")) { value = px; } else { value = (int) px; } } else if (split[1].equalsIgnoreCase("mm")) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, Float.parseFloat(split[0]), context.getResources().getDisplayMetrics()); if (split[0].contains(".")) { value = px; } else { value = (int) px; } } else if (split[1].equalsIgnoreCase("pt")) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, Float.parseFloat(split[0]), context.getResources().getDisplayMetrics()); if (split[0].contains(".")) { value = px; } else { value = (int) px; } } else if (split[1].equalsIgnoreCase("sp")) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, Float.parseFloat(split[0]), context.getResources().getDisplayMetrics()); if (split[0].contains(".")) { value = px; } else { value = (int) px; } } else if (split[1].equals("%")) { ViewParent parent = view.getParent(); float pixels = 0; if (parent == null || !(parent instanceof View)) { pixels = context.getResources().getDisplayMetrics().widthPixels; //use best guess for width or height dpi if (split[0].equalsIgnoreCase("y") || split[0].equalsIgnoreCase("top") || split[0].equalsIgnoreCase("bottom")) { pixels = context.getResources().getDisplayMetrics().heightPixels; } } else { pixels = ((View) parent).getWidth(); if (split[0].equalsIgnoreCase("y") || split[0].equalsIgnoreCase("top") || split[0].equalsIgnoreCase("bottom")) { pixels = ((View) parent).getHeight(); } } float percent = 0; if (pixels != 0) percent = Float.valueOf(split[0]) / 100 * pixels; if (split[0].contains(".")) { value = percent; } else { value = (int) percent; } } else { Log.w("droidQuery", "invalid units for Object with key " + key); return null; } } return value; }
From source file:com.edible.ocr.CaptureActivity.java
/** * Displays information relating to the result of OCR, and requests a translation if necessary. * /*from w w w.java2 s. co m*/ * @param ocrResult Object representing successful OCR results * @return True if a non-null result was received for OCR */ boolean handleOcrDecode(OcrResult ocrResult) { lastResult = ocrResult; // Test whether the result is null if (ocrResult.getText() == null || ocrResult.getText().equals("")) { Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); return false; } // Turn off capture-related UI elements shutterButton.setVisibility(View.GONE); statusViewBottom.setVisibility(View.GONE); statusViewTop.setVisibility(View.GONE); cameraButtonView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView bitmapImageView = (ImageView) findViewById(R.id.image_view); lastBitmap = ocrResult.getBitmap(); if (lastBitmap == null) { bitmapImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)); } else { bitmapImageView.setImageBitmap(lastBitmap); } // Display the recognized text TextView sourceLanguageTextView = (TextView) findViewById(R.id.source_language_text_view); sourceLanguageTextView.setText(sourceLanguageReadable); TextView ocrResultTextView = (TextView) findViewById(R.id.ocr_result_text_view); ocrResultTextView.setText(stripNoise(ocrResult.getText())); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - ocrResult.getText().length() / 4); ocrResultTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView translationLanguageLabelTextView = (TextView) findViewById( R.id.translation_language_label_text_view); TextView translationLanguageTextView = (TextView) findViewById(R.id.translation_language_text_view); TextView translationTextView = (TextView) findViewById(R.id.translation_text_view); if (isTranslationActive) { // Handle translation text fields translationLanguageLabelTextView.setVisibility(View.VISIBLE); translationLanguageTextView.setText(targetLanguageReadable); translationLanguageTextView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL), Typeface.NORMAL); translationLanguageTextView.setVisibility(View.VISIBLE); // Activate/re-activate the indeterminate progress indicator translationTextView.setVisibility(View.GONE); progressView.setVisibility(View.VISIBLE); setProgressBarVisibility(true); // Get the translation asynchronously new TranslateAsyncTask(this, sourceLanguageCodeTranslation, targetLanguageCodeTranslation, stripNoise(ocrResult.getText())).execute(); } else { translationLanguageLabelTextView.setVisibility(View.GONE); translationLanguageTextView.setVisibility(View.GONE); translationTextView.setVisibility(View.GONE); progressView.setVisibility(View.GONE); setProgressBarVisibility(false); } return true; }