List of usage examples for android.widget ImageView getWidth
@ViewDebug.ExportedProperty(category = "layout") public final int getWidth()
From source file:com.ptapp.activity.SessionsFragment.java
@Override public void bindCollectionItemView(Context context, View view, final int groupId, int indexInGroup, int dataIndex, Object tag) { if (mCursor == null || !mCursor.moveToPosition(dataIndex)) { LOGW(TAG, "Can't bind collection view item, dataIndex=" + dataIndex + (mCursor == null ? ": cursor is null" : ": bad data index.")); return;// w w w . j a v a 2 s . c o m } Log.v(TAG, "test collection view cursor data: " + mCursor.getString(0) + ", " + mCursor.getString(1) + ", " + mCursor.getString(2) + ", " + mCursor.getString(3) + ", "); final String groupJid = mCursor.getString(SessionsQuery.GROUP_JID); final String classSubjectId = mCursor.getString(SessionsQuery.CLASS_SUBJECT_ID); if (classSubjectId == null) { return; } // first, read session info from cursor and put it in convenience variables final String courseTitle = mCursor.getString(SessionsQuery.GROUP_NAME); /*final String courseTitle = mCursor.getString(SessionsQuery.SUBJECT_TITLE); final String className = mCursor.getString(SessionsQuery.CLASS_TITLE) + "-" + mCursor.getString(SessionsQuery.SECTION_TITLE);*/ /*final String educatorId = mCursor.getString(SessionsQuery.EDUCATOR_ID); final String classId = mCursor.getString(SessionsQuery.CLASS_ID); final String studentId = mCursor.getString(SessionsQuery.STUDENT_ID);*/ /*final String sessionAbstract = mCursor.getString(SessionsQuery.ABSTRACT); final long sessionStart = mCursor.getLong(SessionsQuery.SESSION_START); final long sessionEnd = mCursor.getLong(SessionsQuery.SESSION_END); final String roomName = mCursor.getString(SessionsQuery.ROOM_NAME); int sessionColor = mCursor.getInt(SessionsQuery.COLOR);*/ int sessionColor = 0; sessionColor = sessionColor == 0 ? getResources().getColor(R.color.default_session_color) : sessionColor; /*final String snippet = mIsSearchCursor ? mCursor.getString(SessionsQuery.SNIPPET) : null; final Spannable styledSnippet = mIsSearchCursor ? buildStyledSnippet(snippet) : null; final boolean starred = mCursor.getInt(SessionsQuery.IN_MY_SCHEDULE) != 0; final String[] tags = mCursor.getString(SessionsQuery.TAGS).split(",");*/ // now let's compute a few pieces of information from the data, which we will use // later to decide what to render where /*final boolean hasLivestream = !TextUtils.isEmpty(mCursor.getString( SessionsQuery.LIVESTREAM_URL));*/ final long now = UIUtils.getCurrentTime(context); /*final boolean happeningNow = now >= sessionStart && now <= sessionEnd;*/ // text that says "LIVE" if session is live, or empty if session is not live /*final String liveNowText = hasLivestream ? " " + UIUtils.getLiveBadgeText(context, sessionStart, sessionEnd) : "";*/ final String liveNowText = ""; // get reference to all the views in the layout we will need final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); final TextView shortSubtitleView = (TextView) view.findViewById(R.id.session_subtitle_short); /*final TextView snippetView = (TextView) view.findViewById(R.id.session_snippet);*/ final TextView abstractView = (TextView) view.findViewById(R.id.session_abstract); final TextView categoryView = (TextView) view.findViewById(R.id.session_category); final View boxView = view.findViewById(R.id.info_box); final View sessionTargetView = view.findViewById(R.id.session_target); final View grpmsgView = (ImageView) view.findViewById(R.id.session_grp_msg); if (sessionColor == 0) { // use default sessionColor = mDefaultSessionColor; } sessionColor = UIUtils.scaleSessionColorToDefaultBG(sessionColor); ImageView photoView = (ImageView) view.findViewById(R.id.session_photo_colored); if (photoView != null) { if (!mPreloader.isDimensSet()) { final ImageView finalPhotoView = photoView; photoView.post(new Runnable() { @Override public void run() { mPreloader.setDimens(finalPhotoView.getWidth(), finalPhotoView.getHeight()); } }); } // colored photoView.setColorFilter(UIUtils.setColorAlpha(sessionColor, UIUtils.SESSION_PHOTO_SCRIM_ALPHA)); } else { photoView = (ImageView) view.findViewById(R.id.session_photo); } ((BaseActivity) getActivity()).getLPreviewUtils().setViewName(photoView, "photo_" + classSubjectId); // when we load a photo, it will fade in from transparent so the // background of the container must be the session color to avoid a white flash ViewParent parent = photoView.getParent(); if (parent != null && parent instanceof View) { ((View) parent).setBackgroundColor(sessionColor); } else { photoView.setBackgroundColor(sessionColor); } //String photo = mCursor.getString(SessionsQuery.PHOTO_URL); int subjPath = R.drawable.nophotoavailable; //TODO:Temporary task to generate screenshots if (courseTitle != null) { if (courseTitle.contains("English")) { subjPath = R.drawable.logo_english; } else if (courseTitle.contains("Math")) { subjPath = R.drawable.logo_math; } else if (courseTitle.contains("Punjabi")) { subjPath = R.drawable.course_punjabi; } else if (courseTitle.contains("Hindi")) { subjPath = R.drawable.course_hindi; } else if (courseTitle.contains("German")) { subjPath = R.drawable.course_german; } else if (courseTitle.contains("Dutch")) { subjPath = R.drawable.course_dutch; } else if (courseTitle.contains("Science")) { subjPath = R.drawable.course_science; } else if (courseTitle.contains("French")) { subjPath = R.drawable.course_french; } } /*if (!TextUtils.isEmpty(photo)) {*/ //mImageLoader.loadImage(photo, photoView, true /*crop*/); Picasso.with(context) // .load(subjPath) // .placeholder(CommonConstants.LOADING) // .error(CommonConstants.ERROR_IMAGE) // .fit() // .into(photoView); /*} else { // cleaning the (potentially) recycled photoView, in case this session has no photo: photoView.setImageDrawable(null); }*/ // render title /*titleView.setText(courseTitle == null ? "?" : courseTitle);*/ titleView.setText(courseTitle == null ? "?" : courseTitle); // render subtitle into either the subtitle view, or the short subtitle view, as available if (subtitleView != null) { /*subtitleView.setText(UIUtils.formatSessionSubtitle( sessionStart, sessionEnd, roomName, mBuffer, context) + liveNowText);*/ //subtitleView.setText(className == null ? "?" : className); } else if (shortSubtitleView != null) { //Dummy data /*shortSubtitleView.setText("25");*/ shortSubtitleView.setText(mCursor.getString(SessionsQuery.MEMBER_COUNT)); shortSubtitleView.setGravity(Gravity.RIGHT); /*shortSubtitleView.setText(UIUtils.formatSessionSubtitle( sessionStart, sessionEnd, roomName, mBuffer, context, true) + liveNowText);*/ //shortSubtitleView.setText(className == null ? "?" : className); } // render category if (categoryView != null) { /*categoryView.setText(className == null ? "?" : className);*/ } // if a snippet view is available, render the session snippet there. /*if (snippetView != null) { *//*if (mIsSearchCursor) { // render the search snippet into the snippet view snippetView.setText(styledSnippet); } else { // render speaker names and abstracts into the snippet view mBuffer.setLength(0); if (!TextUtils.isEmpty(speakerNames)) { mBuffer.append(speakerNames).append(". "); } if (!TextUtils.isEmpty(sessionAbstract)) { mBuffer.append(sessionAbstract); } snippetView.setText(mBuffer.toString()); }*//* }*/ if (abstractView != null && !mIsSearchCursor) { // render speaker names and abstracts into the abstract view mBuffer.setLength(0); /*if (!TextUtils.isEmpty(speakerNames)) { mBuffer.append(speakerNames).append("\n\n"); } if (!TextUtils.isEmpty(sessionAbstract)) { mBuffer.append(sessionAbstract); }*/ abstractView.setText(mBuffer.toString()); } // in expanded mode, the box background color follows the session color if (useExpandedMode()) { boxView.setBackgroundColor(sessionColor); } /*// show or hide the "in my schedule" indicator view.findViewById(R.id.indicator_in_schedule).setVisibility(starred ? View.VISIBLE : View.INVISIBLE);*/ // if we are in condensed mode and this card is the hero card (big card at the top // of the screen), set up the message card if necessary. if (!useExpandedMode() && groupId == HERO_GROUP_ID) { // this is the hero view, so we might want to show a message card final boolean cardShown = setupMessageCard(view); // if this is the wide hero layout, show or hide the card or the session abstract // view, as appropriate (they are mutually exclusive). final View cardContainer = view.findViewById(R.id.message_card_container_wide); final View abstractContainer = view.findViewById(R.id.session_abstract); if (cardContainer != null && abstractContainer != null) { cardContainer.setVisibility(cardShown ? View.VISIBLE : View.GONE); abstractContainer.setVisibility(cardShown ? View.GONE : View.VISIBLE); abstractContainer.setBackgroundColor(sessionColor); } } // if this session is live right now, display the "LIVE NOW" icon on top of it View liveNowBadge = view.findViewById(R.id.live_now_badge); if (liveNowBadge != null) { liveNowBadge.setVisibility(View.INVISIBLE); //liveNowBadge.setVisibility(happeningNow && hasLivestream ? View.VISIBLE : View.GONE); } // if this view is clicked, open the session details view final View finalPhotoView = photoView; final int studentGroupId = mCursor.getInt(SessionsQuery.GROUP_ID); sessionTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCallbacks.onSessionSelected(classSubjectId, courseTitle, groupJid, studentGroupId, finalPhotoView); } }); // animate this card if (dataIndex > mMaxDataIndexAnimated) { mMaxDataIndexAnimated = dataIndex; } //if this view is clicked, open group messages chatting screen if (grpmsgView != null) { grpmsgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i(TAG, "grp msg image clicked, opening group messages screen"); Intent intent = new Intent(getActivity(), EducatorGroupMsgActivity.class); startActivity(intent); } }); } }
From source file:com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment.java
@Override public void onBindViewHolder(final ContactListFragment.ContactItemViewHolder holder, final int position) { final int verifiedPosition = holder.getAdapterPosition(); final VCard vcard = vCards.get(verifiedPosition); if (vcard != null) { if (checkedVCards.contains(position)) { holder.getName().setChecked(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.getName().getCheckMarkDrawable().setColorFilter(ThemeUtils.primaryAccentColor(), PorterDuff.Mode.SRC_ATOP); }/*from w w w . j av a 2 s . c o m*/ } else { holder.getName().setChecked(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.getName().getCheckMarkDrawable().clearColorFilter(); } } holder.getName().setText(getDisplayName(vcard)); // photo if (vcard.getPhotos().size() > 0) { Photo firstPhoto = vcard.getPhotos().get(0); String url = firstPhoto.getUrl(); byte[] data = firstPhoto.getData(); if (data != null && data.length > 0) { Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length); RoundedBitmapDrawable drawable = BitmapUtils .bitmapToCircularBitmapDrawable(context.getResources(), thumbnail); holder.getBadge().setImageDrawable(drawable); } else if (url != null) { ImageView badge = holder.getBadge(); SimpleTarget target = new SimpleTarget<Drawable>() { @Override public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) { holder.getBadge().setImageDrawable(resource); } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); holder.getBadge().setImageDrawable(errorDrawable); } }; DisplayUtils.downloadIcon(context, url, target, R.drawable.ic_user, badge.getWidth(), badge.getHeight()); } } else { try { holder.getBadge() .setImageDrawable(TextDrawable.createNamedAvatar(holder.getName().getText().toString(), context.getResources().getDimension(R.dimen.list_item_avatar_icon_radius))); } catch (Exception e) { holder.getBadge().setImageResource(R.drawable.ic_user); } } // Checkbox holder.setVCardListener(new View.OnClickListener() { @Override public void onClick(View v) { holder.getName().setChecked(!holder.getName().isChecked()); if (holder.getName().isChecked()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.getName().getCheckMarkDrawable().setColorFilter(ThemeUtils.primaryAccentColor(), PorterDuff.Mode.SRC_ATOP); } if (!checkedVCards.contains(verifiedPosition)) { checkedVCards.add(verifiedPosition); } if (checkedVCards.size() == 1) { EventBus.getDefault().post(new VCardToggleEvent(true)); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.getName().getCheckMarkDrawable().clearColorFilter(); } if (checkedVCards.contains(verifiedPosition)) { checkedVCards.remove(verifiedPosition); } if (checkedVCards.size() == 0) { EventBus.getDefault().post(new VCardToggleEvent(false)); } } } }); } }
From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java
@Override public void handle(final Activity activity, final CancellableTask task, final Callback callback) { try {//from ww w . jav a 2 s .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;/*from w ww . ja v a 2s. 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:it.configure.imageloader.zoom.PhotoViewAttacher.java
private void checkMatrixBounds() { final ImageView imageView = getImageView(); if (null == imageView) { return;//from w w w . j a va2 s .c o m } final RectF rect = getDisplayRect(getDisplayMatrix()); if (null == rect) { return; } final float height = rect.height(), width = rect.width(); float deltaX = 0, deltaY = 0; final int viewHeight = imageView.getHeight(); if (height <= viewHeight) { switch (mScaleType) { case FIT_START: deltaY = -rect.top; break; case FIT_END: deltaY = viewHeight - height - rect.top; break; default: deltaY = (viewHeight - height) / 2 - rect.top; break; } } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = viewHeight - rect.bottom; } final int viewWidth = imageView.getWidth(); if (width <= viewWidth) { switch (mScaleType) { case FIT_START: deltaX = -rect.left; break; case FIT_END: deltaX = viewWidth - width - rect.left; break; default: deltaX = (viewWidth - width) / 2 - rect.left; break; } mScrollEdge = EDGE_BOTH; } else if (rect.left > 0) { mScrollEdge = EDGE_LEFT; deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; mScrollEdge = EDGE_RIGHT; } else { mScrollEdge = EDGE_NONE; } // Finally actually translate the matrix mSuppMatrix.postTranslate(deltaX, deltaY); }
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. ja va2 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.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;/*w w w . ja va 2 s .c o 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; }/*from w ww. j a v a 2s . c om*/ 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: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 {//from w w w . j a v a2s . c o 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; }