List of usage examples for android.widget TextView setTextSize
public void setTextSize(int unit, float size)
From source file:com.example.fragmentdemo.views.PagerSlidingTabStrip.java
private void addTab(final int position, CharSequence title, int iconResId, int iLayoutResId, int iTextId, int iIconLocation) { // final View tabView = ((Activity) getContext()).getLayoutInflater() // .inflate(iLayoutResId, null); // TextView tab_text_textview = (TextView) // tabView.findViewById(iTextId); // tab_text_textview.setText(title); LinearLayout tabView = new LinearLayout(getContext()); tabView.setGravity(Gravity.CENTER);//from ww w.j a v a2 s . c o m TextView tab_text_textview = new TextView(getContext()); tab_text_textview.setId(position); tab_text_textview.setText(title); tab_text_textview.setGravity(Gravity.CENTER_VERTICAL); tab_text_textview.setSingleLine(); // tab_text_textview.setTextColor(tabTextColor); // tab_text_textview.setTextColor(getResources().getColor(R.color.indicator_tab_main_text_color)); XmlPullParser xrp = getResources().getXml(tabTextColor); try { ColorStateList csl = ColorStateList.createFromXml(getResources(), xrp); if (tab_text_textview != null) { tab_text_textview.setTextColor(csl); } } catch (Exception e) { } tab_text_textview.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab_text_textview.setTypeface(tabTypeface, tabTypefaceStyle); LinearLayout.LayoutParams lpText = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if (iconResId != 0) { // tab_text_textview.setCompoundDrawablesWithIntrinsicBounds( // iconResId, 0, 0, 0); // Drawable mDrawable = ((Activity) getContext()).getResources() // .getDrawable(iconResId); // mDrawable.setBounds(0, 0, mDrawable.getMinimumWidth(), // mDrawable.getMinimumHeight()); int iPandding = (int) ((Activity) getContext()).getResources().getDimension(R.dimen.common_padding); ImageView icon = new ImageView(getContext()); icon.setImageResource(iconResId); icon.setScaleType(ScaleType.CENTER_INSIDE); LinearLayout.LayoutParams lpImage = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, iIconHeight); switch (iIconLocation) { case 1: // tab_text_textview.setCompoundDrawables(mDrawable, null, null, // null); tabView.setOrientation(LinearLayout.HORIZONTAL); // tabView.setGravity(Gravity.CENTER_VERTICAL); tabView.addView(icon, lpImage); lpText.leftMargin = iPandding; tabView.addView(tab_text_textview, lpText); break; case 2: // tab_text_textview.setCompoundDrawables(null, mDrawable, null, // null); tabView.setOrientation(LinearLayout.VERTICAL); // tabView.setGravity(Gravity.CENTER_HORIZONTAL); tabView.addView(icon, lpImage); lpText.topMargin = iPandding; tabView.addView(tab_text_textview, lpText); break; case 3: // tab_text_textview.setCompoundDrawables(null, null, mDrawable, // null); tabView.setOrientation(LinearLayout.HORIZONTAL); // tabView.setGravity(Gravity.CENTER_VERTICAL); tabView.addView(tab_text_textview, lpText); lpImage.leftMargin = iPandding; tabView.addView(icon, lpImage); break; case 4: // tab_text_textview.setCompoundDrawables(null, null, null, // mDrawable); tabView.setOrientation(LinearLayout.VERTICAL); // tabView.setGravity(Gravity.CENTER_HORIZONTAL); tabView.addView(tab_text_textview, lpText); lpImage.topMargin = iPandding; tabView.addView(icon, lpImage); break; default: // tab_text_textview.setCompoundDrawables(mDrawable, null, null, // null); tabView.setOrientation(LinearLayout.HORIZONTAL); // tabView.setGravity(Gravity.CENTER_VERTICAL); tabView.addView(icon, lpImage); lpText.leftMargin = iPandding; tabView.addView(tab_text_textview, lpText); break; } // tab_text_textview // .setCompoundDrawablePadding((int) ((Activity) getContext()) // .getResources() // .getDimension(R.dimen.common_padding)); } else { tabView.addView(tab_text_textview, lpText); } tabView.setFocusable(true); tabView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); // tab_text_textview.setPadding(tabPadding, 0, tabPadding, 0); tabsContainer.addView(tabView, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); }
From source file:com.allwinner.theatreplayer.launcher.activity.LaunchActivity.java
private void addTopTextView(String title, int count, int index) { if (mTopTextLayout == null) { mTopTextLayout = (LinearLayout) findViewById(R.id.top_text_layout); }// ww w . j a v a 2 s. co m if (mTopFocusLine == null) { mTopFocusLine = (ImageView) findViewById(R.id.top_focus_line); } LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.leftMargin = (int) getResources().getDimensionPixelSize(R.dimen.navigation_home_to_left); LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams2.leftMargin = (int) getResources().getDimensionPixelSize(R.dimen.navigation_home_margin_left); if (mTopTextView == null) { mTopTextView = new TextView[count]; } TextView textView = new TextView(this); textView.setText(title); // if (index == 0) { // textView.setTextColor(getResources().getColor(R.color.blue)); // mTopTextLayout.addView(textView, layoutParams); // } else { textView.setTextColor(getResources().getColor(R.color.white)); if (mPageCount < 5) { mTopTextLayout.addView(textView, layoutParams2); } else { mTopTextLayout.addView(textView, layoutParams); } // } textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.view_page_text_size)); mTopTextView[index] = textView; if (mTopTextView[index] != null) { mTopTextView[index].setTag(index); mTopTextView[index].setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { int tag = (Integer) arg0.getTag(); mViewPager.setCurrentItem(tag); } }); } }
From source file:com.cairoconfessions.MainActivity.java
public void addLocation(View view) { TextView newView = new TextView(this); AutoCompleteTextView addLoc = ((AutoCompleteTextView) findViewById(R.id.addLocation)); String newLoc = addLoc.getText().toString(); ViewGroup locList = ((ViewGroup) findViewById(R.id.locations)); boolean notFound = true; for (int i = 0; i < locList.getChildCount(); i++) { if (newLoc.equals(((TextView) locList.getChildAt(i)).getText().toString())) notFound = false;/*from www. j a v a 2 s . co m*/ break; } if (Arrays.asList(COUNTRIES).contains(newLoc) && notFound) { newView.setText(newLoc); newView.setClickable(true); newView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { addItem(view); } }); float scale = getResources().getDisplayMetrics().density; newView.setGravity(17); newView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30); newView.setBackgroundResource(R.drawable.city2); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (150 * scale)); lp.setMargins((int) (0 * scale), (int) (0 * scale), (int) (0 * scale), (int) (2 * scale)); newView.setLayoutParams(lp); locList.addView(newView, 0); addLoc.setText(""); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(addLoc.getWindowToken(), 0); addLoc.setCursorVisible(false); } else { Toast.makeText(this, "Invalid location", Toast.LENGTH_LONG).show(); } }
From source file:com.edible.ocr.CaptureActivity.java
/** * Displays information relating to the result of OCR, and requests a translation if necessary. * /*from w ww . 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(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; }
From source file:terse.a1.TerseActivity.java
private void viewPath9display(String path, LayoutParams widgetParams) { String explain;// w ww . ja v a2 s.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:edu.sfsu.cs.orange.ocr.CaptureActivity.java
/** * Displays information relating to the result of OCR, and requests a translation if necessary. * /*w w w . j a v a 2 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(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:com.arlib.floatingsearchview.FloatingSearchView.java
private int getSuggestionItemHeight(SearchSuggestion suggestion) { int leftRightMarginsWidth = Util.dpToPx(124); //todo improve efficiency TextView textView = new TextView(getContext()); textView.setTypeface(Typeface.DEFAULT); textView.setText(suggestion.getBody(), TextView.BufferType.SPANNABLE); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mSuggestionsTextSizePx); int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(mSuggestionsList.getWidth() - leftRightMarginsWidth, View.MeasureSpec.AT_MOST); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(widthMeasureSpec, heightMeasureSpec); int heightPlusPadding = textView.getMeasuredHeight() + Util.dpToPx(8); int minHeight = Util.dpToPx(48); int height = heightPlusPadding >= minHeight ? heightPlusPadding : minHeight; return heightPlusPadding >= minHeight ? heightPlusPadding : minHeight; }
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 va 2s .c om*/ 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.initialxy.cordova.themeablebrowser.ThemeableBrowser.java
/** * Display a new browser with the specified URL. * * @param url/* w w w . j a v a 2s .c o m*/ * @param features * @return */ public String showWebPage(final String url, final Options features) { final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { @SuppressLint("NewApi") public void run() { // Let's create the main dialog dialog = new ThemeableBrowserDialog(cordova.getActivity(), android.R.style.Theme_Black_NoTitleBar, features.hardwareback); if (!features.disableAnimation) { dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; } dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setThemeableBrowser(getThemeableBrowser()); // Main container layout ViewGroup main = null; if (features.fullscreen) { main = new FrameLayout(cordova.getActivity()); } else { main = new LinearLayout(cordova.getActivity()); ((LinearLayout) main).setOrientation(LinearLayout.VERTICAL); } // Toolbar layout Toolbar toolbarDef = features.toolbar; FrameLayout toolbar = new FrameLayout(cordova.getActivity()); toolbar.setBackgroundColor(hexStringToColor( toolbarDef != null && toolbarDef.color != null ? toolbarDef.color : "#ffffffff")); toolbar.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, dpToPixels(toolbarDef != null ? toolbarDef.height : TOOLBAR_DEF_HEIGHT))); if (toolbarDef != null && (toolbarDef.image != null || toolbarDef.wwwImage != null)) { try { Drawable background = getImage(toolbarDef.image, toolbarDef.wwwImage, toolbarDef.wwwImageDensity); setBackground(toolbar, background); } catch (Resources.NotFoundException e) { emitError(ERR_LOADFAIL, String.format("Image for toolbar, %s, failed to load", toolbarDef.image)); } catch (IOException ioe) { emitError(ERR_LOADFAIL, String.format("Image for toolbar, %s, failed to load", toolbarDef.wwwImage)); } } // Left Button Container layout LinearLayout leftButtonContainer = new LinearLayout(cordova.getActivity()); FrameLayout.LayoutParams leftButtonContainerParams = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); leftButtonContainerParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; leftButtonContainer.setLayoutParams(leftButtonContainerParams); leftButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); // Right Button Container layout LinearLayout rightButtonContainer = new LinearLayout(cordova.getActivity()); FrameLayout.LayoutParams rightButtonContainerParams = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); rightButtonContainerParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; rightButtonContainer.setLayoutParams(rightButtonContainerParams); rightButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.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)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Back button final Button back = createButton(features.backButton, "back button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.backButton, inAppWebView.getUrl()); if (features.backButtonCanClose && !canGoBack()) { closeDialog(); } else { goBack(); } } }); if (back != null) { back.setEnabled(features.backButtonCanClose); } // Forward button final Button forward = createButton(features.forwardButton, "forward button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.forwardButton, inAppWebView.getUrl()); goForward(); } }); if (forward != null) { forward.setEnabled(false); } // Close/Done button Button close = createButton(features.closeButton, "close button", new View.OnClickListener() { public void onClick(View v) { emitButtonEvent(features.closeButton, inAppWebView.getUrl()); closeDialog(); } }); // Menu button Spinner menu = features.menu != null ? new MenuSpinner(cordova.getActivity()) : null; if (menu != null) { menu.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); menu.setContentDescription("menu button"); setButtonImages(menu, features.menu, DISABLED_ALPHA); // We are not allowed to use onClickListener for Spinner, so we will use // onTouchListener as a fallback. menu.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { emitButtonEvent(features.menu, inAppWebView.getUrl()); } return false; } }); if (features.menu.items != null) { HideSelectedAdapter<EventLabel> adapter = new HideSelectedAdapter<EventLabel>( cordova.getActivity(), android.R.layout.simple_spinner_item, features.menu.items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); menu.setAdapter(adapter); menu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (inAppWebView != null && i < features.menu.items.length) { emitButtonEvent(features.menu.items[i], inAppWebView.getUrl(), i); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } } // Title final TextView title = features.title != null ? new TextView(cordova.getActivity()) : null; final TextView subtitle = features.title != null ? new TextView(cordova.getActivity()) : null; if (title != null) { FrameLayout.LayoutParams titleParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT); titleParams.gravity = Gravity.CENTER; title.setLayoutParams(titleParams); title.setSingleLine(); title.setEllipsize(TextUtils.TruncateAt.END); title.setGravity(Gravity.CENTER | Gravity.TOP); title.setTextColor( hexStringToColor(features.title.color != null ? features.title.color : "#000000ff")); title.setTypeface(title.getTypeface(), Typeface.BOLD); title.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8); FrameLayout.LayoutParams subtitleParams = new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT); titleParams.gravity = Gravity.CENTER; subtitle.setLayoutParams(subtitleParams); subtitle.setSingleLine(); subtitle.setEllipsize(TextUtils.TruncateAt.END); subtitle.setGravity(Gravity.CENTER | Gravity.BOTTOM); subtitle.setTextColor(hexStringToColor( features.title.subColor != null ? features.title.subColor : "#000000ff")); subtitle.setTextSize(TypedValue.COMPLEX_UNIT_PT, 6); subtitle.setVisibility(View.GONE); if (features.title.staticText != null) { title.setGravity(Gravity.CENTER); title.setText(features.title.staticText); } else { subtitle.setVisibility(View.VISIBLE); } } // WebView inAppWebView = new WebView(cordova.getActivity()); final ViewGroup.LayoutParams inAppWebViewParams = features.fullscreen ? new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) : new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0); if (!features.fullscreen) { ((LinearLayout.LayoutParams) inAppWebViewParams).weight = 1; } inAppWebView.setLayoutParams(inAppWebViewParams); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new ThemeableBrowserClient(thatWebView, new PageLoadListener() { @Override public void onPageStarted(String url) { if (inAppWebView != null && title != null && features.title != null && features.title.staticText == null && features.title.showPageTitle && features.title.loadingText != null) { title.setText(features.title.loadingText); subtitle.setText(url); } } @Override public void onPageFinished(String url, boolean canGoBack, boolean canGoForward) { if (inAppWebView != null && title != null && features.title != null && features.title.staticText == null && features.title.showPageTitle) { title.setText(inAppWebView.getTitle()); subtitle.setText(inAppWebView.getUrl()); } if (back != null) { back.setEnabled(canGoBack || features.backButtonCanClose); } if (forward != null) { forward.setEnabled(canGoForward); } } }); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(features.zoom); settings.setDisplayZoomControls(false); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null || appSettings.getBoolean("ThemeableBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext() .getDir("themeableBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (features.clearcache) { CookieManager.getInstance().removeAllCookie(); } else if (features.clearsessioncache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add buttons to either leftButtonsContainer or // rightButtonsContainer according to user's alignment // configuration. int leftContainerWidth = 0; int rightContainerWidth = 0; if (features.customButtons != null) { for (int i = 0; i < features.customButtons.length; i++) { final BrowserButton buttonProps = features.customButtons[i]; final int index = i; Button button = createButton(buttonProps, String.format("custom button at %d", i), new View.OnClickListener() { @Override public void onClick(View view) { if (inAppWebView != null) { emitButtonEvent(buttonProps, inAppWebView.getUrl(), index); } } }); if (ALIGN_RIGHT.equals(buttonProps.align)) { rightButtonContainer.addView(button); rightContainerWidth += button.getLayoutParams().width; } else { leftButtonContainer.addView(button, 0); leftContainerWidth += button.getLayoutParams().width; } } } // Back and forward buttons must be added with special ordering logic such // that back button is always on the left of forward button if both buttons // are on the same side. if (forward != null && features.forwardButton != null && !ALIGN_RIGHT.equals(features.forwardButton.align)) { leftButtonContainer.addView(forward, 0); leftContainerWidth += forward.getLayoutParams().width; } if (back != null && features.backButton != null && ALIGN_RIGHT.equals(features.backButton.align)) { rightButtonContainer.addView(back); rightContainerWidth += back.getLayoutParams().width; } if (back != null && features.backButton != null && !ALIGN_RIGHT.equals(features.backButton.align)) { leftButtonContainer.addView(back, 0); leftContainerWidth += back.getLayoutParams().width; } if (forward != null && features.forwardButton != null && ALIGN_RIGHT.equals(features.forwardButton.align)) { rightButtonContainer.addView(forward); rightContainerWidth += forward.getLayoutParams().width; } if (menu != null) { if (features.menu != null && ALIGN_RIGHT.equals(features.menu.align)) { rightButtonContainer.addView(menu); rightContainerWidth += menu.getLayoutParams().width; } else { leftButtonContainer.addView(menu, 0); leftContainerWidth += menu.getLayoutParams().width; } } if (close != null) { if (features.closeButton != null && ALIGN_RIGHT.equals(features.closeButton.align)) { rightButtonContainer.addView(close); rightContainerWidth += close.getLayoutParams().width; } else { leftButtonContainer.addView(close, 0); leftContainerWidth += close.getLayoutParams().width; } } // Add the views to our toolbar toolbar.addView(leftButtonContainer); // Don't show address bar. // toolbar.addView(edittext); toolbar.addView(rightButtonContainer); if (title != null) { int titleMargin = Math.max(leftContainerWidth, rightContainerWidth); FrameLayout.LayoutParams titleParams = (FrameLayout.LayoutParams) title.getLayoutParams(); titleParams.setMargins(titleMargin, 8, titleMargin, 0); toolbar.addView(title); } if (subtitle != null) { int subtitleMargin = Math.max(leftContainerWidth, rightContainerWidth); FrameLayout.LayoutParams subtitleParams = (FrameLayout.LayoutParams) subtitle.getLayoutParams(); subtitleParams.setMargins(subtitleMargin, 0, subtitleMargin, 8); toolbar.addView(subtitle); } if (features.fullscreen) { // If full screen mode, we have to add inAppWebView before adding toolbar. main.addView(inAppWebView); } // Don't add the toolbar if its been disabled if (features.location) { // Add our toolbar to our main view/layout main.addView(toolbar); } if (!features.fullscreen) { // If not full screen, we add inAppWebView after adding toolbar. main.addView(inAppWebView); } WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if (features.hidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }