View width is zero when set to MATCH_PARENT - android

I have an ImageView inside of a LinearLayout which is an item of a RecyclerView. I have all these views' width as MATCH_PARENT.
Now, I'm trying to calculate the heigth using the aspect ratio before the image is loaded so there's no resizing.
But, what I've seen is that before the image is loaded, its width is zero.
The thing is that I'm doing similar things in other parts of the app and it's working fine, I don't really know what I'm missing here.
RecyclerView item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white">
<LinearLayout
...
</LinearLayout>
<!-- This is the image -->
<ImageView
android:id="#+id/descubre_shop_banner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorLightText"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"/>
</LinearLayout>
ViewHolder
mBannerTarget = new Target()
{
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
{
mShopBannerImageView.setImageBitmap(bitmap);
// Wrap content when the images is loaded.
mShopBannerImageView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
mShopBannerImageView.setBackgroundColor(-1);
mShopBannerImageView.setAlpha(1.0f);
Animation fadeOut = new AlphaAnimation(0, 1);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(250);
mShopBannerImageView.startAnimation(fadeOut);
LOADED = true;
}
#Override
public void onBitmapFailed(Drawable errorDrawable)
{
mShopBannerImageView.setBackgroundColor(
mContext.getResources().getColor(android.R.color.holo_red_dark));
mShopBannerImageView.setAlpha(0.2f);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable)
{
// This is 0
Log.d(Properties.TAG, "" + mShopBannerImageView.getWidth());
// Remove the old bitmap
mShopBannerImageView.setImageBitmap(null);
// Set the height using the width and the aspect ratio.
mShopBannerImageView.getLayoutParams().height =
(int) (mShopBannerImageView.getWidth() * shop.getAspectRatio());
// Set a color while loading.
mShopBannerImageView.setBackgroundColor(
mContext.getResources().getColor(R.color.colorAccent));
mShopBannerImageView.setAlpha(0.25f);
}
};
I tried to set the width of the ImageView and its parent as MATCH_PARENT in code but no luck. Any clue of what's going on?
Regards,

The views dimensions is always 0 before being fully created, if you wanted to know the actual width, you have to use the method: post():
view.post(new Runnable() {
#Override
public void run() {
// This is where width would be different than 0
}
});
That being said, you should actually use an other method to keep the ratio than actually calculating it yourself!
See this thread for further information How to scale an Image in ImageView to keep the aspect ratio

Related

How to get ImageView full width when inside a HorizontalScrollView

I'm placing a very wide image inside a HorizontalScrollView.
The ImageView/ScrollView height is dynamic as I've set the height to 0dp and added constraints. Since the ImageView's scale type is fitStart and adjustViewBounds is true - the image's width is being resized.
XML:
<HorizontalScrollView
android:id="#+id/mapScrollView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toTopOf="#id/playButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:id="#+id/mapLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/mapImage"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:scaleType="fitStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.gigi.testmap.activities.quest.QuestMapPathView
android:id="#+id/mapLinesView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="#id/mapImage"
app:layout_constraintEnd_toEndOf="#id/mapImage"
app:layout_constraintStart_toStartOf="#id/mapImage"
app:layout_constraintTop_toTopOf="#id/mapImage" />
</android.support.constraint.ConstraintLayout>
</HorizontalScrollView>
I'm trying to get the ImageView width (total width, visible & invisible part). Getting the ScrollView total width will also help.
My goal is to place buttons on top of the map in positions calculated according to width & height of the rendered ImageView.
I'm loading the image using Glide:
final ImageView mapImage = mActivity.findViewById(R.id.mapImage);
Glide.with(mActivity).load(R.drawable.fullmap).into(mapImage);
mapImage.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mapImage.getWidth(); // --> returns 0
mapImage.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});
I've tried getting the width using tree view observer's global layout listener but all I got is 0. The height is returned correctly though.
Any help will be much appreciated,
Thank you very much.
I have no experience with Glide.
You are setting the all views / containers android:layout_height="0dp"
try first to change it to any other arbitrary value or wrap_content.
you did not attach the code of how you are trying to get the height.
Have you tryed mapImage.getHeight()
For Bitmap, I used to get this way
Glide.with(mContext())
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap bitmap,
Transition<? super Bitmap> transition) {
int w = bitmap.getWidth();
int h = bitmap.getHeight()
}
});
It seems that the image is not fully rendered once the tree view global layout listener is first called (I guess it's because the image width is pretty big) - What I did was to have a check for the image width and only if greater than 0, remove the listener and continue with my code.
final ImageView mapImage = mActivity.findViewById(R.id.mapImage);
Glide.with(mActivity).load(R.drawable.fullmap).into(mapImage);
mapImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (mapImage.getWidth() > 0) {
mapImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//continue width related code here
}
}
});
Maybe not the prefect solution and there is a small delay until the image shows up - but it is ok for my use case.

ImageView expanding container despite adjustViewBounds

I want to wrap an ImageView inside a LinearLayout so that I can center a group of views. However, the original image needs to be scaled down to fit in the ImageView, and the original size expands the LinearLayout, despite my use of adjustViewBounds="true" and an enclosing FrameLayout as suggested by previous questions on SO.
The desired layout should look like this,
but the observed layout looks like this,
as produced by the XML below:
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="project.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
app:layout_heightPercent="32%"
android:orientation="horizontal"
android:background="#b44343"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sample Text"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5555ae">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#2c8c4c"
android:src="#drawable/spades_icon"
android:adjustViewBounds="true"
android:scaleType="centerInside"/>
</FrameLayout>
</LinearLayout>
</android.support.percent.PercentRelativeLayout>
I can't use the other suggestion of setting android:maxHeight="100dp" because I need the height to be relative to that of the screen.
I see that you have added android:adjustViewBounds="true".
You can combine that with android:maxWidth="60dp"
So your imageView should look like this.
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#2c8c4c"
android:src="#drawable/spades_icon"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:scaleType="centerInside"/>
You can change the max width to any number you want.
Things you can do:
1) Set a specific width / height to the FrameLayout enclosing the ImageView and set android:scaleType to centerInside, fitCenter, or fitXY for the ImageViwe.
2) Programatically, in your activity, after onCreate, in onResume for example, you can get the LayoutParams and change the width and height of the ImageView doing you own scaleing. I take this aproach when I scale against the screen widht or height at run time.
EDIT 1
Example of second alternative:
public class TestActivity extends AppCompatActivity {
ImageView imgView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testactivity_layout);
imgView = (ImageView) findViewById(R.id.imgview);
}
#Override
protected void onResume() {
super.onResume();
ViewGroup.LayoutParams params = imgView.getLayoutParams();
params.width = 100;
}
}
Notes:
The width is expressed in pixel.
To get the display metrics:
How to get screen display metrics in application class
To establish a relative width for the ImageView, get the width of the display and calculate the desireed % as the width of the image.
Based on this answer to another question, a solution that removes the whitespace in the LinearLayout while preserving the height and aspect ratio of the image is:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
LinearLayout layout = (LinearLayout) findViewById(R.id.mLinearLayout);
ImageView imageView = (ImageView) findViewById(R.id.mImageView);
TextView textView = (TextView) findViewById(R.id.mTextView);
layout.getLayoutParams().width = textView.getWidth()+imageView.getWidth();
layout.requestLayout();
}
EDIT:
Based on #Juan's answer and these instructions, the following code also achieves the desired result:
#Override
protected void onResume() {
DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager()
.getDefaultDisplay()
.getMetrics(displayMetrics);
ViewGroup.LayoutParams params = imgView.getLayoutParams();
params.height = (int)Math.floor(displayMetrics.heightPixels * 0.32);
}

Change ImageView size in a recyclerview after Picasso.load()?

I have:
a recyclerview with GridLayoutManager
grid item layout with an ImageView in it (with height wrap_content and width match_parent) wrapped in a Framelayout, so the image is bottom|center_horizontal aligned
Picasso loading an image into ImageView asynchronously from the web
Current situation:
The image is loaded into the imageView, but the imageview's size is the recycled grid item's imageview's size.
What I would like to achieve:
After loading the image into the imageview, resize the imageview on runtime (redraw).
What I have tried:
notifyItemChanged() - could do the trick (in theory at least), but I
am not able to check if the current grid item's view is in layout
state, so my app crashed with IllegalStateException
listening to Picasso's load with a Callback, and onSuccess() check the imageview drawable aspectratio and try to resize the imageview itself with
requestLayout(). Did not work. (Well it worked, but only when there
is an animation or something triggering the redraw of the layout. If
there is nothing, then the imageview is not redrawn.)
listening to Picasso's load with a Callback, and onSuccess() start an animation animating the alpha of the imageview. This would trigger the redraw. But this sometimes worked sometimes not(and I don't know why).
What I did was putting an ImageView into FrameLayout and then changing this FrameLayout's size to needed. Hope it would help you.
<FrameLayout
android:id="#+id/frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<ImageView
android:id="#+id/video_thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitStart"
android:adjustViewBounds="true" />
</FrameLayout>
P.S. changing FrameLayout's size:
viewHolder.frame.setMinimumWidth(neededWidth);
Picasso has a function to resize your image. Something like this:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
You can change centerCrop, to play with aspect ratio
I wanna show this using a
Campaign Banner List Using Dynamic Width - Height Example
that:
Create an item_campaign_banner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/campaignImageSuperView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/campaignImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/campaign_image_error_icon"
android:visibility="visible"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"/>
<View
android:id="#+id/campaignSectionLine"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/campaignImage"
android:background="#F2F2F2" />
</RelativeLayout>
</RelativeLayout>
Than create a BannerHolder.java
public class BannerHolder extends RecyclerView.ViewHolder {
private ImageView campaignImage;
private View campaignSectionLine;
private ViewGroup campaignImageSuperView;
public BannerHolder(#NonNull View itemView) {
super(itemView);
campaignImage = (ImageView) itemView.findViewById(R.id.campaignImage);
campaignSectionLine = itemView.findViewById(R.id.campaignSectionLine);
campaignImageSuperView = itemView.findViewById(R.id.campaignImageSuperView);
}
public ImageView getCampaignImage() {
return campaignImage;
}
public ViewGroup getCampaignImageSuperView() {
return campaignImageSuperView;
}
}
Than apply this in onBindViewHolder(#NonNull RecyclerView.ViewHolder incomingHolder, int position) method that
your created YourAdapter.java
if (incomingHolder instanceof BannerHolder) {
BannerHolder bannerHolder = (BannerHolder) incomingHolder;
Banner banner = (Banner) campaigns.get(position);
if(banner != null && banner.getImage() != null && banner.getImage().getWidth() != null && banner.getImage().getHeight() != null) {
Picasso.with(activity)
.load(banner.getImage().getUrl())
.error(R.drawable.campaign_image_error_icon)
.into(bannerHolder.getCampaignImage());
bannerHolder.getCampaignImageSuperView().setMinimumWidth(banner.getImage().getWidth());
bannerHolder.getCampaignImageSuperView().setMinimumHeight(banner.getImage().getHeight());
}
}
That's all!

Fit image to screen width in viewpager in landscape mode in android

I have a VerticalViewPager and I have some images in it. When I rotate my device in landscape mode my ImageView doesn't scale to width of my screen. It fits the height if image instead. I used AspectRatioImageView. It fits the width but VerticalViewPager doesn't scroll down.
Thank you.
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<HackyViewPager
android:id="#+id/vvp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
>
</HackyViewPager>
</RelativeLayout>
Here is rowitemview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:pixlui="http://schemas.android.com/apk/com.neopixl.pixlui"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff" >
<AspectRatioImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/m4_3" />
</LinearLayout>
and here is my instaniateItem of my ImagePageAdapter that extends PagerAdapter:
#Override
public Object instantiateItem(ViewGroup container, int position)
{
Context context = MainActivity.this;
container.requestLayout();
AspectRatioImageView imageView = new AspectRatioImageView(context);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.m4_3));
mAttacher = new PhotoViewAttacher(imageView);
mAttacher.setOnMatrixChangeListener(new OnMatrixChangedListener() {
#Override
public void onMatrixChanged(RectF rect) {
if((int)rect.width()>_width)
viewPager.setLocked(true);
else
viewPager.setLocked(false);
}
});
P.S : The issue is with viewPager height. When I scroll down the image it just goes to the other page instead of scrolling the scaled image.
Here's what you need.
This is a good solution I found out.
Android Crop Center of Bitmap
This allows to set the height and your width according to your orientation.
To change the image's scale to full screen, you generally use center crop like this:
yourImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Hope this information was useful..:)
Use android:scalType = "fitxy" in activity code like this imageView.setScaleType(ImageView.ScaleType.FIT_XY);

Android: grow/shrink View over time

I have a view layout like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#color/light_gray"
android:padding="5dip">
<View android:id="#+id/fixedSpace" android:layout_width="fill_parent"
android:layout_height="50dip" android:background="#color/aqua"
android:layout_alignParentBottom="true" android:clickable="true"
android:onClick="onClickStartAnimation" />
<View android:id="#+id/dynamicSpace" android:layout_width="fill_parent"
android:layout_height="200dip" android:background="#color/lime"
android:layout_above="#id/fixedSpace" />
<View android:id="#+id/remainingSpace" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#color/pink"
android:layout_alignParentTop="true" android:layout_above="#id/dynamicSpace" />
</RelativeLayout>
What I want to achieve is basically a grow/shrink behavior of dynamicSpace over the time t. With animations I can produce the following:
t=1:
t=2:
t=3:
However, that doesn't really resize my views, in particular dynamicSpace and remainingSpace. It just animates the view dynamicSpace moving in. But the view "container" already has the space occupied right from the beginning.
Correct would be that the lime colored dynamicSpace starts with 0px and the pink colored remainingSpace takes over, so there is no gray space in between.
Scale the View
Since you say you are doing it over time t, it sounds like a LinearInterpolator is best.
EDIT:
I tried replacing the below with an AsyncTask thread and it is far smoother. I think the key is I keep the thread running in the background and just use it when I want to resize something, thus reducing overhead
Create a custom AnimationListener and put the code for resizing the view in the onAnimationRepeat method.
Then do a dummy animation and set repeat on the animation to infinite. Once the view has reached the final size, set repeat count on the animation to zero (again in onAnimationRepeat):
class ResizeAnimationListener implements AnimationListener{
int finalHeight; // max Height
int resizeAmount; // amount to resize each time
View view; // view to resize
public ResizeAnimationListener(int finalHeight; View view, int resizeAmount) {
super();
finalHeight; = finalHeight;
this.resizeAmount = resizeAmount;
this.view = view;
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
int newHeight;
int currentHeight;
current = view.getMeasuredHeight();
newHeight= currentHeight+ resizeAmount;
if(newHeight> finalHeight){
// check if reached final height
// set new height to the final height
newHeight = finalHeight;
// set repeat count to zero so we don't have any more repeats
anim.setRepeatCount(0);
}
// set new height
LayoutParams params = view.getLayoutParams();
params.height = newHeight;
v.setLayoutParams(params);
}
#Override
public void onAnimationStart(Animation animation) {
}
};
class DummyAnimation extends Animation{}
float frameRate = 1000/30;
DummyAnimation anim = new DummyAnimation();
anim.setDuration((long)frameRate);
anim.setRepeatCount(Animation.INFINITE);
ResizeAnimationListener animListener = new ResizeAnimationListener(((View)view.getParent()).getHeight(), view, 25);
anim.setAnimationListener(animListener);
view.startAnimation(anim);
I made this work on my own app . However, views anchored to the view I'm resizing (and thus moving on screen when I resize my view) seem to glitch out. Probably related to repeated resizing rather than anything else, but just a warning. Maybe someone else knows why?

Categories

Resources