Related
I want to create a custom TextView which is square by default but if the text cannot fit into, the height increases automatically to accommodate the content.
I tried setting the height to wrap_content and overriding the onMeasure() like so:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newHeight = heightMeasureSpec > widthMeasureSpec ? heightMeasureSpec : widthMeasureSpec;
super.onMeasure(widthMeasureSpec, newHeight);
}
But that did not work.
When content is less, it's fine.
But when content is more, the height should expand but it doesn't. A lot of text is clipping out
You could use setMinHeight to achieve this purpose
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int minHeight = MeasureSpec.getSize(widthMeasureSpec);
setMinHeight(minHeight);
}
And set wrap_content to layout_height in layout:
<com.test.SquareTextView
android:id="#+id/squareTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" />
Update for RecyclerView:
1.Get screen width inside Activity class:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
2.Pass it to adapter and set when create item view:
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View root = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.my_item, viewGroup, false);
root.setMinimumHeight(screenWidth);
return new ViewHolder(root);
}
I have a custom ViewGroup that has a child ViewPager. The ViewPager is fed by a PagerAdapter that provides a LinearLayout to the ViewPager which has LayoutParams of WRAP_CONTENT on both height and width.
The view displays correctly but when the child.measure() method is called on the ViewPager it does not return the actual dimensions of the LinearLayout but seems to fill all the remaining space.
Any ideas why this is happening and how to amend it?
I wasn't very happy with the accepted answer (nor with the pre-inflate-all-views solution in the comments), so I put together a ViewPager that takes its height from the first available child. It does this by doing a second measurement pass, allowing you to steal the first child's height.
A better solution would be to make a new class inside the android.support.v4.view package that implements a better version of onMeasure (with access to package-visible methods like populate())
For the time being, though, the solution below suits me fine.
public class HeightWrappingViewPager extends ViewPager {
public HeightWrappingViewPager(Context context) {
super(context);
}
public HeightWrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec)
== MeasureSpec.AT_MOST;
if(wrapHeight) {
/**
* The first super.onMeasure call made the pager take up all the
* available height. Since we really wanted to wrap it, we need
* to remeasure it. Luckily, after that call the first child is
* now available. So, we take the height from it.
*/
int width = getMeasuredWidth(), height = getMeasuredHeight();
// Use the previously measured width but simplify the calculations
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
/* If the pager actually has any children, take the first child's
* height and call that our own */
if(getChildCount() > 0) {
View firstChild = getChildAt(0);
/* The child was previously measured with exactly the full height.
* Allow it to wrap this time around. */
firstChild.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
height = firstChild.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Looking at the internals of the ViewPager class in the compatibility jar:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// For simple implementation, or internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
...
}
It would appear that the ViewPager implementation does not measure the children views but just sets the ViewPager to be one standard view based on what the parent is passing in. When you pass wrap_content, since the view pager doesn't actually measure its content it takes up the full available area.
My recommendation would be to set a static size on your ViewPager based on the size of your child views. If this is impossible (for instance, the child views can vary) you'll either need to pick a maximum size and deal with the extra space in some views OR extend ViewPager and provide a onMeasure that measure the children. One issue you will run into is that the view pager was designed not to vary in width as different views are shown, so you'll probably be forced to pick a size and stay with it
If you setTag(position) in the instantiateItem of your PageAdapter:
#Override
public Object instantiateItem(ViewGroup collection, int page) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.page_item , null);
view.setTag(page);
then can retrieve the view (page of the adapter) with an OnPageChangeListener, measure it, and resize your ViewPager:
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
pager = findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
resizePager(position);
}
});
public void resizePager(int position) {
View view = pager.findViewWithTag(position);
if (view == null)
return;
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
//The layout params must match the parent of the ViewPager
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width , height);
pager.setLayoutParams(params);
}
}
Following the above example I discovered that measuring the height of the child views does not always return accurate results. The solution is to measure the height of any static views (defined in the xml) and then add the height of the fragment that is dynamically created at the bottom.
In my case the static element was the PagerTitleStrip, which I also had to Override in order to enable the use of match_parent for the width in landscape mode.
So here is my take on the code from Delyan:
public class WrappingViewPager extends ViewPager {
public WrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super has to be called in the beginning so the child views can be
// initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() <= 0)
return;
// Check if the selected layout_height mode is set to wrap_content
// (represented by the AT_MOST constraint).
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec)
== MeasureSpec.AT_MOST;
int width = getMeasuredWidth();
View firstChild = getChildAt(0);
// Initially set the height to that of the first child - the
// PagerTitleStrip (since we always know that it won't be 0).
int height = firstChild.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = 0;
fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
// Just add the height of the fragment:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + fragmentHeight,
MeasureSpec.EXACTLY);
// super has to be called again so the new specs are treated as
// exact measurements.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}}
And the custom PagerTitleStrip:
public class MatchingPagerTitleStrip extends android.support.v4.view.PagerTitleStrip {
public MatchingPagerTitleStrip(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
#Override
protected void onMeasure(int arg0, int arg1) {
int size = MeasureSpec.getSize(arg0);
int newWidthSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(newWidthSpec, arg1);
}}
Cheers!
With Reference of above solutions, added some more statement to get maximum height of view pager child.
Refer the below code.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super has to be called in the beginning so the child views can be
// initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() <= 0)
return;
// Check if the selected layout_height mode is set to wrap_content
// (represented by the AT_MOST constraint).
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
int width = getMeasuredWidth();
int childCount = getChildCount();
int height = getChildAt(0).getMeasuredHeight();
int fragmentHeight = 0;
for (int index = 0; index < childCount; index++) {
View firstChild = getChildAt(index);
// Initially set the height to that of the first child - the
// PagerTitleStrip (since we always know that it won't be 0).
height = firstChild.getMeasuredHeight() > height ? firstChild.getMeasuredHeight() : height;
int fHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, index)).getView());
fragmentHeight = fHeight > fragmentHeight ? fHeight : fragmentHeight;
}
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
// Just add the height of the fragment:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + fragmentHeight, MeasureSpec.EXACTLY);
// super has to be called again so the new specs are treated as
// exact measurements.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
better change
height = firstChild.getMeasuredHeight();
to
height = firstChild.getMeasuredHeight() + getPaddingTop() + getPaddingBottom();
I want to override onMeasure() method in my custom View. And if user specify height to be LayoutParams.WRAP_CONTENT then I want to give a particular minimum height. Right now my custom View takes up the whole screen with both WRAP_CONTENT as well as MATCH_PARENT, unless height is specified explicitly. I was thinking of checking LayoutParams in onMeasure() when I stumbled upon this code in View class:
/**
* The layout parameters associated with this view and used by the parent
* {#link android.view.ViewGroup} to determine how this view should be
* laid out.
* {#hide}
*/
protected ViewGroup.LayoutParams mLayoutParams;
Despite being protected it is not accessible in custom View class, noticed the #hide annotation in comment? Although I can get this by calling public method getLayoutParams() but now I am wondering is onMeasure() the right place for the checking of params and assigning min height value? My current onMeasure() looks like this.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int height = getDefaultSize(getSuggestedMinimumHeight(),
heightMeasureSpec);
final int width = getDefaultSize(getSuggestedMinimumWidth(),
widthMeasureSpec);
int w = resolveSize(width, widthMeasureSpec);
int h = resolveSize(height, heightMeasureSpec);
setMeasuredDimension(w, h);
}
I read source code and solved my problem by giving min width and min height to resolveSize() method. Which solved my problem:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = resolveSize(myMinWidth, widthMeasureSpec);
int h = resolveSize(myMinHeight, heightMeasureSpec);
setMeasuredDimension(w, h);
}
I have a custom ViewGroup that has a child ViewPager. The ViewPager is fed by a PagerAdapter that provides a LinearLayout to the ViewPager which has LayoutParams of WRAP_CONTENT on both height and width.
The view displays correctly but when the child.measure() method is called on the ViewPager it does not return the actual dimensions of the LinearLayout but seems to fill all the remaining space.
Any ideas why this is happening and how to amend it?
I wasn't very happy with the accepted answer (nor with the pre-inflate-all-views solution in the comments), so I put together a ViewPager that takes its height from the first available child. It does this by doing a second measurement pass, allowing you to steal the first child's height.
A better solution would be to make a new class inside the android.support.v4.view package that implements a better version of onMeasure (with access to package-visible methods like populate())
For the time being, though, the solution below suits me fine.
public class HeightWrappingViewPager extends ViewPager {
public HeightWrappingViewPager(Context context) {
super(context);
}
public HeightWrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec)
== MeasureSpec.AT_MOST;
if(wrapHeight) {
/**
* The first super.onMeasure call made the pager take up all the
* available height. Since we really wanted to wrap it, we need
* to remeasure it. Luckily, after that call the first child is
* now available. So, we take the height from it.
*/
int width = getMeasuredWidth(), height = getMeasuredHeight();
// Use the previously measured width but simplify the calculations
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
/* If the pager actually has any children, take the first child's
* height and call that our own */
if(getChildCount() > 0) {
View firstChild = getChildAt(0);
/* The child was previously measured with exactly the full height.
* Allow it to wrap this time around. */
firstChild.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
height = firstChild.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Looking at the internals of the ViewPager class in the compatibility jar:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// For simple implementation, or internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
...
}
It would appear that the ViewPager implementation does not measure the children views but just sets the ViewPager to be one standard view based on what the parent is passing in. When you pass wrap_content, since the view pager doesn't actually measure its content it takes up the full available area.
My recommendation would be to set a static size on your ViewPager based on the size of your child views. If this is impossible (for instance, the child views can vary) you'll either need to pick a maximum size and deal with the extra space in some views OR extend ViewPager and provide a onMeasure that measure the children. One issue you will run into is that the view pager was designed not to vary in width as different views are shown, so you'll probably be forced to pick a size and stay with it
If you setTag(position) in the instantiateItem of your PageAdapter:
#Override
public Object instantiateItem(ViewGroup collection, int page) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.page_item , null);
view.setTag(page);
then can retrieve the view (page of the adapter) with an OnPageChangeListener, measure it, and resize your ViewPager:
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
pager = findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
resizePager(position);
}
});
public void resizePager(int position) {
View view = pager.findViewWithTag(position);
if (view == null)
return;
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
//The layout params must match the parent of the ViewPager
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width , height);
pager.setLayoutParams(params);
}
}
Following the above example I discovered that measuring the height of the child views does not always return accurate results. The solution is to measure the height of any static views (defined in the xml) and then add the height of the fragment that is dynamically created at the bottom.
In my case the static element was the PagerTitleStrip, which I also had to Override in order to enable the use of match_parent for the width in landscape mode.
So here is my take on the code from Delyan:
public class WrappingViewPager extends ViewPager {
public WrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super has to be called in the beginning so the child views can be
// initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() <= 0)
return;
// Check if the selected layout_height mode is set to wrap_content
// (represented by the AT_MOST constraint).
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec)
== MeasureSpec.AT_MOST;
int width = getMeasuredWidth();
View firstChild = getChildAt(0);
// Initially set the height to that of the first child - the
// PagerTitleStrip (since we always know that it won't be 0).
int height = firstChild.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = 0;
fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
// Just add the height of the fragment:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + fragmentHeight,
MeasureSpec.EXACTLY);
// super has to be called again so the new specs are treated as
// exact measurements.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}}
And the custom PagerTitleStrip:
public class MatchingPagerTitleStrip extends android.support.v4.view.PagerTitleStrip {
public MatchingPagerTitleStrip(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
#Override
protected void onMeasure(int arg0, int arg1) {
int size = MeasureSpec.getSize(arg0);
int newWidthSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(newWidthSpec, arg1);
}}
Cheers!
With Reference of above solutions, added some more statement to get maximum height of view pager child.
Refer the below code.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super has to be called in the beginning so the child views can be
// initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() <= 0)
return;
// Check if the selected layout_height mode is set to wrap_content
// (represented by the AT_MOST constraint).
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
int width = getMeasuredWidth();
int childCount = getChildCount();
int height = getChildAt(0).getMeasuredHeight();
int fragmentHeight = 0;
for (int index = 0; index < childCount; index++) {
View firstChild = getChildAt(index);
// Initially set the height to that of the first child - the
// PagerTitleStrip (since we always know that it won't be 0).
height = firstChild.getMeasuredHeight() > height ? firstChild.getMeasuredHeight() : height;
int fHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, index)).getView());
fragmentHeight = fHeight > fragmentHeight ? fHeight : fragmentHeight;
}
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
// Just add the height of the fragment:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + fragmentHeight, MeasureSpec.EXACTLY);
// super has to be called again so the new specs are treated as
// exact measurements.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
better change
height = firstChild.getMeasuredHeight();
to
height = firstChild.getMeasuredHeight() + getPaddingTop() + getPaddingBottom();
What's the correct way of overriding onMeasure()? I've seen various approaches. For example, Professional Android Development uses MeasureSpec to calculate the dimensions, then ends with a call to setMeasuredDimension(). For example:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
}
On the other hand, as per this post, the "correct" way is to use MeasureSpec, call setMeasuredDimensions(), followed by a call to setLayoutParams(), and ending with a call to super.onMeasure(). For example:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
So which is the right way? Neither approach has worked 100% for me.
I guess really what I'm asking is does anyone know of a tutorial that explains onMeasure(), layout, dimensions of child views etc.?
The other solutions are not comprehensive. They may work in some cases, and are a good place to start, but they may are not guaranteed to work.
When onMeasure gets called you may or may not have the rights to change the size. The values that are passed to your onMeasure (widthMeasureSpec, heightMeasureSpec) contain information about what your child view is allowed to do. Currently there are three values:
MeasureSpec.UNSPECIFIED - You can be as big as you'd like
MeasureSpec.AT_MOST - As big as you want (up to the spec size), This is parentWidth in your example.
MeasureSpec.EXACTLY - No choice. Parent has chosen.
This is done so that Android can make multiple passes to find the right size for each item, see here for more details.
If you do not follow these rules, your approach is not guaranteed to work.
For example if you want to check if you're allowed to change the size at all you can do the following:
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
Using this information you will know whether you can modify the values as in your code. Or if you are required to do something different. A quick and easy way to resolve your desired size is to use one of the following methods:
int resolveSizeAndState (int size, int measureSpec, int childMeasuredState)
int resolveSize (int size, int measureSpec)
While the first is only available on Honeycomb, the second is available on all versions.
Note: You may find that resizeWidth or resizeHeight are always false. I found this to be the case if I was requesting MATCH_PARENT. I was able to fix this by requesting WRAP_CONTENT on my parent layout and then during the UNSPECIFIED phase requesting a size of Integer.MAX_VALUE. Doing so gives you the max size your parent allows on the next pass through onMeasure.
The documentation is the authority on this matter: http://developer.android.com/guide/topics/ui/how-android-draws.html and http://developer.android.com/guide/topics/ui/custom-components.html
To summarize: at the end of your overridden onMeasure method you should call setMeasuredDimension.
You should not call super.onMeasure after calling setMeasuredDimension, that will just erase whatever you set. In some situations you might want to call the super.onMeasure first and then modify the results by calling setMeasuredDimension.
Don't call setLayoutParams in onMeasure. Layout happens in a second pass after measuring.
I think it depends on the parent which you are overriding.
For example, if you are extending a ViewGroup (like FrameLayout), when you have measured the size, you should call like below
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
because you may want to ViewGroup to do rest work (do some stuffs on child view)
If you are extending a View (like ImageView), you can just call this.setMeasuredDimension(width, height);, because the parent class will just do something like you have done usually.
In a word, if you want some features your parent class offers free you should call super.onMeasure() (pass MeasureSpec.EXACTLY mode measure spec usually), otherwise call this.setMeasuredDimension(width, height); is enough.
If changing the views size inside of onMeasure all you need is the setMeasuredDimension call. If you are changing the size outside of onMeasure you need to call setLayoutParams. For instance changing the size of a text view when the text is changed.
Depends on the control you are using. The instructions in the documentation work for some controls (TextView, Button, ...), but not for others (LinearLayout, ...). The way that worked very well for me was to call the super once I am done. Based on the article in the below link.
http://humptydevelopers.blogspot.in/2013/05/android-view-overriding-onmeasure.html
here is how I solved the problem:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
....
setMeasuredDimension( measuredWidth, measuredHeight );
widthMeasureSpec = MeasureSpec.makeMeasureSpec( measuredWidth, MeasureSpec.EXACTLY );
heightMeasureSpec = MeasureSpec.makeMeasureSpec( measuredHeight, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
Moreover it was necessary for the ViewPager component
I guess, setLayoutParams and recalculating the measurements is a workaround to resize the child views correctly, as this is usually done in the derived class's onMeasure.
However, this rarely works correct (for whatever reason...), better invoke measureChildren (when deriving a ViewGroup) or try something similar when necessary.
you can take this piece of code as an example of onMeasure()::
public class MyLayerLayout extends RelativeLayout {
public MyLayerLayout(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int currentChildCount = getChildCount();
for (int i = 0; i < currentChildCount; i++) {
View currentChild = getChildAt(i);
//code to find information
int widthPercent = currentChildInfo.getWidth();
int heightPercent = currentChildInfo.getHeight();
//considering we will pass height & width as percentage
int myWidth = (int) Math.round(parentWidth * (widthPercent / 100.0));
int myHeight = (int) Math.round(parentHeight * (heightPercent / 100.0));
//Considering we need to set horizontal & vertical position of the view in parent
AlignmentTraitValue vAlign = currentChildInfo.getVerticalLocation() != null ? currentChildlayerInfo.getVerticalLocation() : currentChildAlignmentTraitValue.TOP;
AlignmentTraitValue hAlign = currentChildInfo.getHorizontalLocation() != null ? currentChildlayerInfo.getHorizontalLocation() : currentChildAlignmentTraitValue.LEFT;
int topPadding = 0;
int leftPadding = 0;
if (vAlign.equals(currentChildAlignmentTraitValue.CENTER)) {
topPadding = (parentHeight - myHeight) / 2;
} else if (vAlign.equals(currentChildAlignmentTraitValue.BOTTOM)) {
topPadding = parentHeight - myHeight;
}
if (hAlign.equals(currentChildAlignmentTraitValue.CENTER)) {
leftPadding = (parentWidth - myWidth) / 2;
} else if (hAlign.equals(currentChildAlignmentTraitValue.RIGHT)) {
leftPadding = parentWidth - myWidth;
}
LayoutParams myLayoutParams = new LayoutParams(myWidth, myHeight);
currentChildLayoutParams.setMargins(leftPadding, topPadding, 0, 0);
currentChild.setLayoutParams(myLayoutParams);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}