List of usage examples for android.widget ImageView getHeight
@ViewDebug.ExportedProperty(category = "layout") public final int getHeight()
From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java
@Override public void handle(final Activity activity, final CancellableTask task, final Callback callback) { try {// www . ja v a2s. c o m final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName)) .getHttpClient(); final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : ""); String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL; Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) }; String htmlChallenge; if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) { htmlChallenge = lastChallenge.getRight(); } else { htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL, HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient, null, task, false); } lastChallenge = null; Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge); if (challengeMatcher.find()) { final String challenge = challengeMatcher.group(1); HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl( scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey, HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient, null, task); try { InputStream imageStream = responseModel.stream; final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream); final String message; Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>") .matcher(htmlChallenge); if (messageMatcher.find()) message = RegexUtils.removeHtmlTags(messageMatcher.group(1)); else message = null; final Bitmap candidateBitmap; Matcher candidateMatcher = Pattern .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"") .matcher(htmlChallenge); if (candidateMatcher.find()) { Bitmap bmp = null; try { byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT); bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length); } catch (Exception e) { } candidateBitmap = bmp; } else candidateBitmap = null; activity.runOnUiThread(new Runnable() { final int maxX = 3; final int maxY = 3; final boolean[] isSelected = new boolean[maxX * maxY]; @SuppressLint("InlinedApi") @Override public void run() { LinearLayout rootLayout = new LinearLayout(activity); rootLayout.setOrientation(LinearLayout.VERTICAL); if (candidateBitmap != null) { ImageView candidateView = new ImageView(activity); candidateView.setImageBitmap(candidateBitmap); int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50 + 0.5f); candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize)); candidateView.setScaleType(ImageView.ScaleType.FIT_XY); rootLayout.addView(candidateView); } if (message != null) { TextView textView = new TextView(activity); textView.setText(message); CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance); textView.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); rootLayout.addView(textView); } FrameLayout frame = new FrameLayout(activity); frame.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); final ImageView imageView = new ImageView(activity); imageView.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setImageBitmap(challengeBitmap); frame.addView(imageView); final LinearLayout selector = new LinearLayout(activity); selector.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); AppearanceUtils.callWhenLoaded(imageView, new Runnable() { @Override public void run() { selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(), imageView.getHeight())); } }); selector.setOrientation(LinearLayout.VERTICAL); selector.setWeightSum(maxY); for (int y = 0; y < maxY; ++y) { LinearLayout subSelector = new LinearLayout(activity); subSelector.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)); subSelector.setOrientation(LinearLayout.HORIZONTAL); subSelector.setWeightSum(maxX); for (int x = 0; x < maxX; ++x) { FrameLayout switcher = new FrameLayout(activity); switcher.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)); switcher.setTag(new int[] { x, y }); switcher.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int[] coord = (int[]) v.getTag(); int index = coord[1] * maxX + coord[0]; isSelected[index] = !isSelected[index]; v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0) : Color.TRANSPARENT); } }); subSelector.addView(switcher); } selector.addView(subSelector); } frame.addView(selector); rootLayout.addView(frame); Button checkButton = new Button(activity); checkButton.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); checkButton.setText(android.R.string.ok); rootLayout.addView(checkButton); ScrollView dlgView = new ScrollView(activity); dlgView.addView(rootLayout); final Dialog dialog = new Dialog(activity); dialog.setTitle("Recaptcha"); dialog.setContentView(dlgView); dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!task.isCancelled()) { callback.onError("Cancelled"); } } }); dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); dialog.show(); checkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (task.isCancelled()) return; Async.runAsync(new Runnable() { @Override public void run() { try { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("c", challenge)); for (int i = 0; i < isSelected.length; ++i) if (isSelected[i]) pairs.add(new BasicNameValuePair("response", Integer.toString(i))); HttpRequestModel request = HttpRequestModel.builder() .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")) .setCustomHeaders(new Header[] { new BasicHeader(HttpHeaders.REFERER, usingURL) }) .build(); String response = HttpStreamer.getInstance().getStringFromUrl( usingURL, request, httpClient, null, task, false); String hash = ""; Matcher matcher = Pattern.compile( "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<", Pattern.DOTALL).matcher(response); if (matcher.find()) hash = matcher.group(1); if (hash.length() > 0) { Recaptcha2solved.push(publicKey, hash); activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } else { lastChallenge = Pair.of(usingURL, response); throw new RecaptchaException( "incorrect answer (hash is empty)"); } } catch (final Exception e) { Logger.e(TAG, e); if (task.isCancelled()) return; handle(activity, task, callback); } } }); } }); } }); } finally { responseModel.release(); } } else throw new Exception("can't parse recaptcha challenge answer"); } catch (final Exception e) { Logger.e(TAG, e); if (!task.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onError(e.getMessage() != null ? e.getMessage() : e.toString()); } }); } } }
From source file:com.github.colorchief.colorchief.MainActivity.java
private Bitmap decodeImageUri(Uri selectedImage, ImageView imageView) throws FileNotFoundException { // Decode image size (i.e. only read enough of the bitmap to determine its size) BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, imageOptions); int yScale = 1; int xScale = 1; int scale;//w w w.j ava 2 s. c om // To determine the magnitude of the scale, Get the size of ImageView component we are drawing to // (note, this assumes the InageView is already sized to fit the screen area available if ((imageOptions.outHeight > imageView.getHeight()) && (imageView.getHeight() > 0)) { yScale = imageOptions.outHeight / imageView.getHeight(); } if ((imageOptions.outWidth > imageView.getWidth()) && (imageView.getWidth() > 0)) { xScale = imageOptions.outWidth / imageView.getWidth(); } scale = Math.max(xScale, yScale); Log.d(TAG, "ImageView Height:" + Integer.toString(imageView.getHeight())); Log.d(TAG, "ImageView Width :" + Integer.toString(imageView.getWidth())); Log.d(TAG, "Bitmap Height:" + Integer.toString(imageOptions.outHeight)); Log.d(TAG, "Bitmap Width :" + Integer.toString(imageOptions.outWidth)); Log.d(TAG, "Scale :" + Integer.toString(scale)); // Decode bitmap (Scale it) BitmapFactory.Options imageOptionsOut = new BitmapFactory.Options(); imageOptionsOut.inSampleSize = scale; return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, imageOptionsOut); }
From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java
private void setPic(String path, int orientation) { ImageView mImageView = (ImageView) findViewById(R.id.pd_claim_share_image_view); int targetW = mImageView.getWidth(); int targetH = mImageView.getHeight(); mImageAdded = true;//from w w w .j a v a 2 s .co m image = PDUIImageUtils.getResizedBitmap(path, 500, 500, orientation); mImageView.setImageBitmap(image); twitterURI = saveBitmapToInternalCache(this, image); mImageView.setVisibility(View.VISIBLE); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(PDUIClaimActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { new AlertDialog.Builder(PDUIClaimActivity.this) .setTitle(getString(R.string.pd_storage_permissions_title_string)) .setMessage(getString(R.string.pd_storage_permission_rationale_string)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(PDUIClaimActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 123); } }).setNegativeButton(android.R.string.no, null).create().show(); } else { showAddPictureChoiceDialog(); } } }); }
From source file:com.github.colorchief.colorchief.MainActivity.java
private boolean clickInImage(int x, int y, ImageView imageView) { //ImageView imageViewer = (ImageView) findViewById(R.id.imageView); if (imageView.getVisibility() != View.VISIBLE) { return false; }/* w w w .java 2 s . c o m*/ int[] imageViewCoords = new int[2]; imageView.getLocationOnScreen(imageViewCoords); float[] imageViewMatrix = new float[9]; imageView.getImageMatrix().getValues(imageViewMatrix); float scaleX = imageViewMatrix[Matrix.MSCALE_X]; float scaleY = imageViewMatrix[Matrix.MSCALE_Y]; Bitmap bitmap = null; int bitmapWidth = 0; int bitmapHeight = 0; try { bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); bitmapWidth = bitmap.getWidth(); bitmapHeight = bitmap.getHeight(); } catch (NullPointerException npe) { Log.e(TAG, "Failed to extract Bitmap from ImageView: " + npe); } //assuming Bitmap is centred in imageViewer int scaledBitmapWidth = Math.round(bitmapWidth * scaleX); int scaledBitmapHeight = Math.round(bitmapHeight * scaleY); int xOffsetBitmap2imageViewer = (imageView.getWidth() - scaledBitmapWidth) / 2; int yOffsetBitmap2imageViewer = (imageView.getHeight() - scaledBitmapHeight) / 2; // get total bitmap offset vs. screen origin int xTotalOffset = imageViewCoords[0] + xOffsetBitmap2imageViewer; int yTotalOffset = imageViewCoords[1] + yOffsetBitmap2imageViewer; if ((x >= xTotalOffset) && (x <= xTotalOffset + scaledBitmapWidth) && (y >= yTotalOffset) && (y <= yTotalOffset + scaledBitmapHeight)) { return true; } else { return false; } }
From source file:github.daneren2005.dsub.fragments.SelectDirectoryFragment.java
private void setupTextDisplay(final View header) { final TextView titleView = (TextView) header.findViewById(R.id.select_album_title); if (playlistName != null) { titleView.setText(playlistName); } else if (podcastName != null) { titleView.setText(podcastName);/*from w ww . j a va 2 s . c o m*/ titleView.setPadding(0, 6, 4, 8); } else if (name != null) { titleView.setText(name); if (artistInfo != null) { titleView.setPadding(0, 6, 4, 8); } } else if (share != null) { titleView.setVisibility(View.GONE); } int songCount = 0; Set<String> artists = new HashSet<String>(); Set<Integer> years = new HashSet<Integer>(); Integer totalDuration = 0; for (Entry entry : entries) { if (!entry.isDirectory()) { songCount++; if (entry.getArtist() != null) { artists.add(entry.getArtist()); } if (entry.getYear() != null) { years.add(entry.getYear()); } Integer duration = entry.getDuration(); if (duration != null) { totalDuration += duration; } } } final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist); if (podcastDescription != null || artistInfo != null) { artistView.setVisibility(View.VISIBLE); String text = podcastDescription != null ? podcastDescription : artistInfo.getBiography(); Spanned spanned = null; if (text != null) { spanned = Html.fromHtml(text); } artistView.setText(spanned); artistView.setSingleLine(false); final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength); artistView.setLines(minLines); artistView.setTextAppearance(context, android.R.style.TextAppearance_Small); final Spanned spannedText = spanned; artistView.setOnClickListener(new View.OnClickListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { if (artistView.getMaxLines() == minLines) { // Use LeadingMarginSpan2 to try to make text flow around image Display display = context.getWindowManager().getDefaultDisplay(); ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art); coverArtView.measure(display.getWidth(), display.getHeight()); int height, width; ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView .getLayoutParams(); if (coverArtView.getDrawable() != null) { height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom(); width = coverArtView.getWidth() + coverArtView.getPaddingRight(); } else { height = coverArtView.getHeight(); width = coverArtView.getWidth() + coverArtView.getPaddingRight(); } float textLineHeight = artistView.getPaint().getTextSize(); int lines = (int) Math.ceil(height / textLineHeight); SpannableString ss = new SpannableString(spannedText); ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); View linearLayout = header.findViewById(R.id.select_album_text_layout); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout .getLayoutParams(); int[] rules = params.getRules(); rules[RelativeLayout.RIGHT_OF] = 0; params.leftMargin = vlp.rightMargin; artistView.setText(ss); artistView.setMaxLines(100); vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams(); vlp.leftMargin = width; } else { artistView.setMaxLines(minLines); } } }); artistView.setMovementMethod(LinkMovementMethod.getInstance()); } else if (topTracks) { artistView.setText(R.string.menu_top_tracks); artistView.setVisibility(View.VISIBLE); } else if (showAll) { artistView.setText(R.string.menu_show_all); artistView.setVisibility(View.VISIBLE); } else if (artists.size() == 1) { String artistText = artists.iterator().next(); if (years.size() == 1) { artistText += " - " + years.iterator().next(); } artistView.setText(artistText); artistView.setVisibility(View.VISIBLE); } else { artistView.setVisibility(View.GONE); } TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count); TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length); if (podcastDescription != null || artistInfo != null) { songCountView.setVisibility(View.GONE); songLengthView.setVisibility(View.GONE); } else { String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount, songCount); songCountView.setText(s.toUpperCase()); songLengthView.setText(Util.formatDuration(totalDuration)); } }
From source file:com.github.colorchief.colorchief.MainActivity.java
private int[] clickImagePixelLocation(int x, int y, ImageView imageView) { int[] pixelLocation = new int[2]; //ImageView imageViewer = (ImageView) findViewById(R.id.imageView); //Bitmap bitmap = null; //Drawable displayedDrawable = null; int bitmapWidth; int bitmapHeight; try {/* www. j a v a2 s. co m*/ //bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); bitmapWidth = bitmapScaledOriginal.getWidth(); bitmapHeight = bitmapScaledOriginal.getHeight(); } catch (NullPointerException npe) { Log.e(TAG, "Failed to extract Bitmap from ImageView or " + "access width and height parameters: " + npe); pixelLocation[0] = pixelLocation[1] = 0; return pixelLocation; } float[] imageMatrixValues = new float[9]; imageView.getImageMatrix().getValues(imageMatrixValues); float scaleX = imageMatrixValues[Matrix.MSCALE_X]; float scaleY = imageMatrixValues[Matrix.MSCALE_Y]; int[] imageViewerLoc = new int[2]; imageView.getLocationOnScreen(imageViewerLoc); //assuming Bitmap is centred in imageViewer int xOffsetBitmap2imageViewer = (imageView.getWidth() - Math.round(bitmapWidth * scaleX)) / 2; int yOffsetBitmap2imageViewer = (imageView.getHeight() - Math.round(bitmapHeight * scaleY)) / 2; // get total bitmap offset vs. screen origin int xTotalOffset = imageViewerLoc[0] + xOffsetBitmap2imageViewer; int yTotalOffset = imageViewerLoc[1] + yOffsetBitmap2imageViewer; int xLocationScaledBitmap = x - xTotalOffset; int yLocationScaledBitmap = y - yTotalOffset; pixelLocation[0] = Math.round(xLocationScaledBitmap / scaleX); pixelLocation[1] = Math.round(yLocationScaledBitmap / scaleY); Log.d(TAG, "Pixel location x,y = " + Integer.toString(pixelLocation[0]) + ", " + Integer.toString(pixelLocation[1])); if (pixelLocation[0] < 0) pixelLocation[0] = 0; if (pixelLocation[0] > (bitmapWidth - 1)) pixelLocation[0] = (bitmapWidth - 1); if (pixelLocation[1] < 0) pixelLocation[1] = 0; if (pixelLocation[1] > (bitmapHeight - 1)) pixelLocation[1] = (bitmapHeight - 1); return pixelLocation; }
From source file:github.popeen.dsub.fragments.SelectDirectoryFragment.java
private void setupTextDisplay(final View header) { final TextView titleView = (TextView) header.findViewById(R.id.select_album_title); if (playlistName != null) { titleView.setText(playlistName); } else if (podcastName != null) { Collections.reverse(entries); titleView.setText(podcastName);/*from w w w. j av a 2 s . c o m*/ titleView.setPadding(0, 6, 4, 8); } else if (name != null) { titleView.setText(name); if (artistInfo != null) { titleView.setPadding(0, 6, 4, 8); } } else if (share != null) { titleView.setVisibility(View.GONE); } int songCount = 0; Set<String> artists = new HashSet<String>(); Set<Integer> years = new HashSet<Integer>(); totalDuration = 0; for (Entry entry : entries) { if (!entry.isDirectory()) { songCount++; if (entry.getArtist() != null) { artists.add(entry.getArtist()); } if (entry.getYear() != null) { years.add(entry.getYear()); } Integer duration = entry.getDuration(); if (duration != null) { totalDuration += duration; } } } String artistName = ""; bookDescription = "Could not collect any info about the book at this time"; try { artistName = artists.iterator().next(); String endpoint = "getBookDirectory"; if (Util.isTagBrowsing(context)) { endpoint = "getBook"; } SharedPreferences prefs = Util.getPreferences(context); String url = Util.getRestUrl(context, endpoint) + "&id=" + directory.getId() + "&f=json"; Log.w("GetInfo", url); String artist, title; int year = 0; artist = title = ""; try { artist = artists.iterator().next(); } catch (Exception e) { Log.w("GetInfoArtist", e.toString()); } try { title = titleView.getText().toString(); } catch (Exception e) { Log.w("GetInfoTitle", e.toString()); } try { year = years.iterator().next(); } catch (Exception e) { Log.w("GetInfoYear", e.toString()); } BookInfoAPIParams params = new BookInfoAPIParams(url, artist, title, year); bookInfo = new BookInfoAPI(context).execute(params).get(); bookDescription = bookInfo[0]; bookReader = bookInfo[1]; } catch (Exception e) { Log.w("GetInfoError", e.toString()); } if (bookDescription.equals("noInfo")) { bookDescription = "The server has no description for this book"; } final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist); if (podcastDescription != null || artistInfo != null || bookDescription != null) { artistView.setVisibility(View.VISIBLE); String text = ""; if (bookDescription != null) { text = bookDescription; } if (podcastDescription != null) { text = podcastDescription; } if (artistInfo != null) { text = artistInfo.getBiography(); } Spanned spanned = null; if (text != null) { String newText = ""; try { if (!artistName.equals("")) { newText += "<b>" + context.getResources().getString(R.string.main_artist) + "</b>: " + artistName + "<br/>"; } } catch (Exception e) { } try { if (totalDuration > 0) { newText += "<b>" + context.getResources().getString(R.string.album_book_reader) + "</b>: " + bookReader + "<br/>"; } } catch (Exception e) { } try { if (totalDuration > 0) { newText += "<b>" + context.getResources().getString(R.string.album_book_length) + "</b>: " + Util.formatDuration(totalDuration) + "<br/>"; } } catch (Exception e) { } try { newText += text + "<br/>"; } catch (Exception e) { } spanned = Html.fromHtml(newText); } artistView.setText(spanned); artistView.setSingleLine(false); final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength); artistView.setLines(minLines); artistView.setTextAppearance(context, android.R.style.TextAppearance_Small); final Spanned spannedText = spanned; artistView.setOnClickListener(new View.OnClickListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { if (artistView.getMaxLines() == minLines) { // Use LeadingMarginSpan2 to try to make text flow around image Display display = context.getWindowManager().getDefaultDisplay(); ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art); coverArtView.measure(display.getWidth(), display.getHeight()); int height, width; ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView .getLayoutParams(); if (coverArtView.getDrawable() != null) { height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom(); width = coverArtView.getWidth() + coverArtView.getPaddingRight(); } else { height = coverArtView.getHeight(); width = coverArtView.getWidth() + coverArtView.getPaddingRight(); } float textLineHeight = artistView.getPaint().getTextSize(); int lines = (int) Math.ceil(height / textLineHeight) + 1; SpannableString ss = new SpannableString(spannedText); ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); View linearLayout = header.findViewById(R.id.select_album_text_layout); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout .getLayoutParams(); int[] rules = params.getRules(); rules[RelativeLayout.RIGHT_OF] = 0; params.leftMargin = vlp.rightMargin; artistView.setText(ss); artistView.setMaxLines(100); vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams(); vlp.leftMargin = width; } else { artistView.setMaxLines(minLines); } } }); artistView.setMovementMethod(LinkMovementMethod.getInstance()); } else if (topTracks) { artistView.setText(R.string.menu_top_tracks); artistView.setVisibility(View.VISIBLE); } else if (showAll) { artistView.setText(R.string.menu_show_all); artistView.setVisibility(View.VISIBLE); } else if (artists.size() == 1) { String artistText = artists.iterator().next(); if (years.size() == 1) { artistText += " - " + years.iterator().next(); } artistView.setText(artistText); artistView.setVisibility(View.VISIBLE); } else { artistView.setVisibility(View.GONE); } TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count); TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length); if (podcastDescription != null || artistInfo != null) { songCountView.setVisibility(View.GONE); songLengthView.setVisibility(View.GONE); } else { String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount, songCount); songCountView.setVisibility(View.GONE); songLengthView.setVisibility(View.GONE); } }
From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java
private void processFrame() { long newTime = System.currentTimeMillis(); long time = newTime - mLastTime; boolean end = false; if (time > 60) { Log.e("LONG", "Frame time took too long! Time: " + time + " Last process frame: " + mLastFrameTime + " Count: " + mBackgroundCount + " Level: " + mLevel); }/*from www . ja va 2 s .co m*/ // We don't want to jump too far so, if real time is > 60 treat it as 33. On screen will seem to slow // down instaead of "jump" if (time > 60) { time = 33; } // Score is based on time + presents. Right now 100 point per second played. No presents yet if (mLevel < 6) { mScore += time; } if (mIsTv) { mScoreText.setText(mScoreLabel + ": " + NumberFormat.getNumberInstance().format((mScore / 10))); } else { mScoreText.setText(NumberFormat.getNumberInstance().format((mScore / 10))); } float scroll = mElfVelX * time; // Do collision detection first... // The elf can't collide if it is within 2 seconds of colliding previously. if (mElfIsHit) { if ((newTime - mElfHitTime) > 2000) { // Move to next state. if (mElfState < 4) { mElfState++; AnalyticsManager.sendEvent(getString(R.string.analytics_screen_rocket), getString(R.string.analytics_action_rocket_hit), null, mElfState); if (mElfState == 4) { mSoundPool.play(mGameOverSound, 1.0f, 1.0f, 2, 0, 1.0f); // No more control... mControlView.setOnTouchListener(null); mElfAccelY = 0.0f; if (mJetThrustStream != 0) { mSoundPool.stop(mJetThrustStream); } } } updateElf(false); mElfIsHit = false; } } else if (mElfState == 4) { // Don't do any collision detection for parachute elf. Just let him fall... } else { // Find the obstacle(s) we might be colliding with. It can only be one of the first 3 obstacles. for (int i = 0; i < 3; i++) { View view = mObstacleLayout.getChildAt(i); if (view == null) { // No more obstacles... break; } int[] tmp = new int[2]; view.getLocationOnScreen(tmp); // If the start of this view is past the center of the elf, we are done if (tmp[0] > mElfPosX) { break; } if (RelativeLayout.class.isInstance(view)) { // this is an obstacle layout. View topView = view.findViewById(R.id.top_view); View bottomView = view.findViewById(R.id.bottom_view); if ((topView != null) && topView.getVisibility() == View.VISIBLE) { topView.getLocationOnScreen(tmp); Rect obsRect = new Rect(tmp[0], tmp[1], tmp[0] + topView.getWidth(), tmp[1] + topView.getHeight()); if (obsRect.contains((int) mElfPosX, (int) mElfPosY + mElfBitmap.getHeight() / 2)) { handleCollision(); } } if (!mElfIsHit) { if ((bottomView != null) && bottomView.getVisibility() == View.VISIBLE) { bottomView.getLocationOnScreen(tmp); Rect obsRect = new Rect(tmp[0], tmp[1], tmp[0] + bottomView.getWidth(), tmp[1] + bottomView.getHeight()); if (obsRect.contains((int) mElfPosX, (int) mElfPosY + mElfBitmap.getHeight() / 2)) { // Special case for the mammoth obstacle... if (bottomView.getTag() != null) { if (((mElfPosX - tmp[0]) / (float) bottomView.getWidth()) > 0.25f) { // We are over the mammoth not the spike. lower the top of the rect and test again. obsRect.top = (int) (tmp[1] + ((float) bottomView.getHeight() * 0.18f)); if (obsRect.contains((int) mElfPosX, (int) mElfPosY + mElfBitmap.getHeight() / 2)) { handleCollision(); } } } else { handleCollision(); } } } } } else if (FrameLayout.class.isInstance(view)) { // Present view FrameLayout frame = (FrameLayout) view; if (frame.getChildCount() > 0) { ImageView presentView = (ImageView) frame.getChildAt(0); presentView.getLocationOnScreen(tmp); Rect presentRect = new Rect(tmp[0], tmp[1], tmp[0] + presentView.getWidth(), tmp[1] + presentView.getHeight()); mElfLayout.getLocationOnScreen(tmp); Rect elfRect = new Rect(tmp[0], tmp[1], tmp[0] + mElfLayout.getWidth(), tmp[1] + mElfLayout.getHeight()); if (elfRect.intersect(presentRect)) { // We got a present! mPresentCount++; if (mPresentCount < 4) { mSoundPool.play(mScoreSmallSound, 1.0f, 1.0f, 2, 0, 1.0f); mScore += 1000; // 100 points. Score is 10x displayed score. mPlus100.setVisibility(View.VISIBLE); if (mElfPosY > (mScreenHeight / 2)) { mPlus100.setY(mElfPosY - (mElfLayout.getHeight() + mPlus100.getHeight())); } else { mPlus100.setY(mElfPosY + mElfLayout.getHeight()); } mPlus100.setX(mElfPosX); if (m100Anim.hasStarted()) { m100Anim.reset(); } mPlus100.startAnimation(m100Anim); } else { mSoundPool.play(mScoreBigSound, 1.0f, 1.0f, 2, 0, 1.0f); mScore += 5000; // 500 points. Score is 10x displayed score. if (!mRainingPresents) { mPresentCount = 0; } mPlus500.setVisibility(View.VISIBLE); if (mElfPosY > (mScreenHeight / 2)) { mPlus500.setY(mElfPosY - (mElfLayout.getHeight() + mPlus100.getHeight())); } else { mPlus500.setY(mElfPosY + mElfLayout.getHeight()); } mPlus500.setX(mElfPosX); if (m500Anim.hasStarted()) { m500Anim.reset(); } mPlus500.startAnimation(m500Anim); mPresentBonus = true; } frame.removeView(presentView); } else if (elfRect.left > presentRect.right) { mPresentCount = 0; } } } } } if (mForegroundLayout.getChildCount() > 0) { int currentX = mForegroundScroll.getScrollX(); View view = mForegroundLayout.getChildAt(0); int newX = currentX + (int) scroll; if (newX > view.getWidth()) { newX -= view.getWidth(); mForegroundLayout.removeViewAt(0); } mForegroundScroll.setScrollX(newX); } // Scroll obstacle views if (mObstacleLayout.getChildCount() > 0) { int currentX = mObstacleScroll.getScrollX(); View view = mObstacleLayout.getChildAt(0); int newX = currentX + (int) scroll; if (newX > view.getWidth()) { newX -= view.getWidth(); mObstacleLayout.removeViewAt(0); } mObstacleScroll.setScrollX(newX); } // Scroll the background and foreground if (mBackgroundLayout.getChildCount() > 0) { int currentX = mBackgroundScroll.getScrollX(); View view = mBackgroundLayout.getChildAt(0); int newX = currentX + (int) scroll; if (newX > view.getWidth()) { newX -= view.getWidth(); mBackgroundLayout.removeViewAt(0); if (view.getTag() != null) { Pair<Integer, Integer> pair = (Pair<Integer, Integer>) view.getTag(); int type = pair.first; int level = pair.second; if (type == 0) { if (mBackgrounds[level] != null) { mBackgrounds[level].recycle(); mBackgrounds[level] = null; } else if (mBackgrounds2[level] != null) { mBackgrounds2[level].recycle(); mBackgrounds2[level] = null; } } else if (type == 1) { if (mExitTransitions[level] != null) { mExitTransitions[level].recycle(); mExitTransitions[level] = null; } } else if (type == 2) { if (mEntryTransitions[level] != null) { mEntryTransitions[level].recycle(); mEntryTransitions[level] = null; } } } if (mBackgroundCount == 5) { if (mLevel < 6) { // Pre-fetch next levels backgrounds // end level uses the index 1 background... int level = (mLevel == 5) ? 1 : (mLevel + 1); BackgroundLoadTask task = new BackgroundLoadTask(getResources(), mLevel + 1, BACKGROUNDS[level], EXIT_TRANSITIONS[mLevel], // Exit transitions are for the current level... ENTRY_TRANSITIONS[level], mScaleX, mScaleY, mBackgrounds, mBackgrounds2, mExitTransitions, mEntryTransitions, mScreenWidth, mScreenHeight); task.execute(); addNextImages(mLevel, true); addNextObstacles(mLevel, 2); } // Fetch first set of obstacles if the next level changes from woods to cave or cave to factory if (mLevel == 1) { // Next level will be caves. Get bitmaps for the first 20 obstacles. ObstacleLoadTask task = new ObstacleLoadTask(getResources(), CAVE_OBSTACLES, mCaveObstacles, mCaveObstacleList, 0, 2, mScaleX, mScaleY); task.execute(); } else if (mLevel == 3) { // Next level will be factory. Get bitmaps for the first 20 obstacles. ObstacleLoadTask task = new ObstacleLoadTask(getResources(), FACTORY_OBSTACLES, mFactoryObstacles, mFactoryObstacleList, 0, 2, mScaleX, mScaleY); task.execute(); } mBackgroundCount++; } else if (mBackgroundCount == 7) { // Add transitions and/or next level if (mLevel < 5) { addNextTransitionImages(mLevel + 1); if (mTransitionImagesCount > 0) { addNextObstacleSpacer(mTransitionImagesCount); } addNextImages(mLevel + 1); // First screen of each new level has no obstacles if ((mLevel % 2) == 1) { addNextObstacleSpacer(1); addNextObstacles(mLevel + 1, 1); } else { addNextObstacles(mLevel + 1, 2); } } else if (mLevel == 5) { addNextTransitionImages(mLevel + 1); if (mTransitionImagesCount > 0) { addNextObstacleSpacer(mTransitionImagesCount); } addFinalImages(); } mBackgroundCount++; } else if (mBackgroundCount == 9) { // Either the transition or the next level is showing if (this.mTransitionImagesCount > 0) { mTransitionImagesCount--; } else { if (mLevel == 1) { // Destroy the wood obstacle bitmaps Thread thread = new Thread(new Runnable() { @Override public void run() { synchronized (mWoodObstacles) { for (Bitmap bmp : mWoodObstacles.values()) { bmp.recycle(); } mWoodObstacles.clear(); } } }); thread.start(); } else if (mLevel == 3) { // Destroy the cave obstacle bitmaps Thread thread = new Thread(new Runnable() { @Override public void run() { synchronized (mCaveObstacles) { for (Bitmap bmp : mCaveObstacles.values()) { bmp.recycle(); } mCaveObstacles.clear(); } } }); thread.start(); } else if (mLevel == 5) { // Destroy the factory obstacle bitmaps Thread thread = new Thread(new Runnable() { @Override public void run() { synchronized (mFactoryObstacles) { for (Bitmap bmp : mFactoryObstacles.values()) { bmp.recycle(); } mFactoryObstacles.clear(); } } }); thread.start(); } mLevel++; // Add an event for clearing this level - note we don't increment mLevel as // it's 0-based and we're tracking the previous level. AnalyticsManager.sendEvent(getString(R.string.analytics_screen_rocket), getString(R.string.analytics_action_rocket_level), null, mLevel); // Achievements if (!mHitLevel) { mCleanLevel = true; } mHitLevel = false; if (mLevel == 5) { mPlus100.setSelected(true); mPlus500.setSelected(true); } else if (mLevel == 6) { mPlus100.setSelected(false); mPlus500.setSelected(false); } if (mLevel < 6) { mSoundPool.play(mLevelUpSound, 1.0f, 1.0f, 2, 0, 1.0f); addNextImages(mLevel); addNextObstacles(mLevel, 2); } mBackgroundCount = 0; } } else { if ((mBackgroundCount % 2) == 1) { if (mLevel < 6) { addNextImages(mLevel); addNextObstacles(mLevel, 2); } } mBackgroundCount++; } } int current = mBackgroundScroll.getScrollX(); mBackgroundScroll.setScrollX(newX); if ((mLevel == 6) && (mBackgroundScroll.getScrollX() == current)) { end = true; } } // Check on the elf boolean hitBottom = false; boolean hitTop = false; float deltaY = mElfVelY * time; mElfPosY = mElfLayout.getY() + deltaY; if (mElfPosY < 0.0f) { mElfPosY = 0.0f; mElfVelY = 0.0f; hitTop = true; } else if (mElfPosY > (mScreenHeight - mElfLayout.getHeight())) { mElfPosY = mScreenHeight - mElfLayout.getHeight(); mElfVelY = 0.0f; hitBottom = true; } else { // Remember -Y is up! mElfVelY += (mGravityAccelY * time - mElfAccelY * time); } mElfLayout.setY(mElfPosY); // Rotate the elf to indicate thrust, dive. float rot = (float) (Math.atan(mElfVelY / mElfVelX) * 120.0 / Math.PI); mElfLayout.setRotation(rot); mElf.invalidate(); // Update the time and spawn the next call to processFrame. mLastTime = newTime; mLastFrameTime = System.currentTimeMillis() - newTime; if (!end) { if ((mElfState < 4) || !hitBottom) { if (mLastFrameTime < 16) { mHandler.postDelayed(mGameLoop, 16 - mLastFrameTime); } else { mHandler.post(mGameLoop); } } else { endGame(); } } else { // Whatever the final stuff is, do it here. mPlayPauseButton.setEnabled(false); mPlayPauseButton.setVisibility(View.INVISIBLE); endGame(); } }