Inflated children of custom LinearLayout don't show when overriding onMeasure - android

I'm trying to show a MyCustomLinearLayout which extends LinearLayout. I'm inflating the MyCustomLinearLayout with the android:layout_height="match_parent" attribute.
What I want is to show an ImageView in this MyCustomLinearLayout. The height of this ImageView should be match_parent, and the width should be equal to the height. I'm trying to accomplish this by overriding the onMeasure() method. What happens, is that MyCustomLinearLayout does become square like it should, but the ImageView is not showing.
Below my used code. Please note that this is an extremely simplified version of my problem. The ImageView will be replaced by a more complex component.
public MyCustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_myimageview, this);
setBackgroundColor(getResources().getColor(R.color.blue));
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(height, height);
}
The view_myimageview.xml file:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="#+id/view_myimageview_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_launcher" />
</merge>
So when I override the onMeasure() method, the ImageView is not showing, when I don't override the onMeasure() method, the ImageView shows, but way too small, because the MyCustomLinearLayout's width is too small.

That's not how you override the onMeasure method especially of a default SDK layout. Right now with your code you just made the MyCustomLinearLayout square assigning it a certain value. But, you didn't measured its children so they are sizeless and don't appear on the screen.
I'm not sure this would work but try this:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int size = getMeasuredHeight();
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}
Of course this will basically do the work of onMeasure twice but the ImageView should be now visible filling it's parent. There are other solutions but your question is a bit scarce on details.

Related

Prevent GridView from scaling

How do I keep gridView from needing to scroll by auto adjusting it's height? I would like all items, no matter how many items I add to the gridView to remain on screen without scrolling. Is this possible?
Here is my UI so far.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<GridView
android:id="#+id/gv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tv_header"
android:fadingEdge="none"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
I did try adding a weightSum to the root and weight to gridView but it still requires scrolling.
Update: I also tried using a custom gridview. This did not work, but here is my attempt anyway.
public class CustomGridView extends GridView {
public CustomGridView(Context context) {
super(context);
}
public CustomGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST));
getLayoutParams().height = getMeasuredHeight();
}
}
Thanks in advance!
I have found answer to this. You can set the height of each item in the adapter by using
view.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, resizeValue));
resizeValue is the size that you want to adjust your rows to. To get resizeValue you can pass to the adapter mResizeValue based on the calculations relative to your device screen size. Something like
resizevalue = this.getResources().getDisplayMetrics().heightPixels / (NUM_COLS);
I figured out some other ways of calculating the height of each row based on screen size and then doing something similar, however, this requires that you do these calculations after you set your adapter and then update the changes to the adapter. It seems less efficient but I will share that methodology as well.
private void resizeGridView(GridView gridView, int items, int columns) {
ViewGroup.LayoutParams params = gridView.getLayoutParams();
int oneRowHeight = gridView.getHeight();
int rows = (int) (items / columns);
params.height = oneRowHeight * rows;
gridView.setLayoutParams(params);
}
Then after you set your adapter use
gridView.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (!gridViewResized) {
gridViewResized = true;
resizeGridView(gridView, numItems, numColumns);
}
}
});

Proper way override fixed size custom view

I have a custom view with Yellow background. I plan to add a Red background TextView, with match_parent for both width and height on it. Here's what I had done.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainView = (LinearLayout)this.findViewById(R.id.screen_main);
RateAppBanner rateAppBanner = new RateAppBanner(this);
mainView.addView(rateAppBanner);
}
}
RateAppBanner.java
public class RateAppBanner extends LinearLayout {
public RateAppBanner(Context context) {
super(context);
setOrientation(HORIZONTAL);
LayoutInflater.from(context).inflate(R.layout.rate_app_banner, this, true);
this.setBackgroundColor(Color.YELLOW);
}
}
rate_app_banner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffffff"
android:background="#ffff0000"
android:text="Hello World" />
</LinearLayout>
Now, I would like to have a fixed width & height custom view. I realize, after I'm having fixed width & height custom view, the added TextView doesn't obey match_parent attribute.
Here's the change I had done on custom view.
RateAppBanner.java
public class RateAppBanner extends LinearLayout {
...
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 320;
int desiredHeight = 50;
desiredWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredWidth, getResources().getDisplayMetrics());
desiredHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredHeight, getResources().getDisplayMetrics());
super.onMeasure(desiredWidth, desiredHeight);
//MUST CALL THIS
setMeasuredDimension(desiredWidth, desiredHeight);
}
I realize the added TextView doesn't match_parent anymore!
Now, we can see the Yellow custom view is having fixed size 320x50. I expect the Red TextView will fill up the entire custom view due to match_parent attribute.
However, that's not the case. I believe my implementation for custom view's onMeasure isn't correct. May I know what is the correct way to fix this?
The complete source code can be downloaded from abc.zip
After lots of trial and error and doing research work, final found answer.
You have set measurements for layout but not for child view, so for that you need to put this in onMeasure method,
super.onMeasure(
MeasureSpec.makeMeasureSpec(desiredWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(desiredHeight, MeasureSpec.EXACTLY));
Reference link : Inflated children of custom LinearLayout don't show when overriding onMeasure
And finally it's working :)

wrap_content does not work with custom RelativeLayout

I have created a custom layout which extends RelativeLayout. At the moment, this layout does nothing except overriding the onMeasure method (that I will need later). Here is my code:
public class CustomLayout extends RelativeLayout {
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
}
And I have the following layout file:
<LinearLayout
android:id="#+id/containerLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<...CustomLayout
android:id="#+id/item"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:background="#fff" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="20sp" />
</...CustomLayout>
<RelativeLayout
android:id="#+id/controls"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:background="#0f0" >
</RelativeLayout>
</LinearLayout>
The problem is that the height is null. During my debugging, I have noticed that if I change the CustomLayout to a RelativeLayout it works.
So, it is quite obvious that the problem comes from my CustomLayout, but what do I need to add to make the wrap_content work ?
I have finally found the problem. I change this:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
To this:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
And it works fine.
Explanation
First, the following line was useless:
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
But why does it makes the View's height null?
In fact, I misunderstood the paramaters of the onMeasure method. They are MeasureSpec values. Here is what Google says about this object:
A MeasureSpec encapsulates the layout requirements passed from parent
to child. Each MeasureSpec represents a requirement for either the
width or the height. A MeasureSpec is comprised of a size and a mode.
There are three possible modes:
UNSPECIFIED The parent has not imposed any constraint on the child. It
can be whatever size it wants. EXACTLY The parent has determined an
exact size for the child. The child is going to be given those bounds
regardless of how big it wants to be. AT_MOST The child can be as
large as it wants up to the specified size. MeasureSpecs are
implemented as ints to reduce object allocation. This class is
provided to pack and unpack the tuple into the int
The widthMeasureSpec and heightMeasureSpec values are not only the width and the height of the View. In this case, passing these values to setMeasureDimension are completly wrong because this method actually requires real sizes as parameters.

Making GridView items square

I would like the items of my GridView to be square. There are 2 columns and the items width is fill_parent (e.g. they take as much horizontal space as possible. The items are custom views.
How do I make the items height to be equal to their variable width?
There is a simpler solution when GridView columns are stretched. Just override the onMeasure of the GridView item layout with...
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
Or if you want to extend a View just do something really simple like:
public class SquareImageView extends ImageView
{
public SquareImageView(final Context context)
{
super(context);
}
public SquareImageView(final Context context, final AttributeSet attrs)
{
super(context, attrs);
}
public SquareImageView(final Context context, final AttributeSet attrs, final int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
final int width = getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
setMeasuredDimension(width, width);
}
#Override
protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh)
{
super.onSizeChanged(w, w, oldw, oldh);
}
}
It's worth noting that super.onMeasure() is not needed. onMeasured requirement is that you must call setMeasuredDimension.
I'm not sure this is possible with the current widgets. Your best bet might be to put your custom view in a custom "SquareView". This view could just contain 1 child view, and force the height to equal the width when its onLayout method is called.
I never tried to do something like that, but I think it shouldn't be too difficult. An alternative (and maybe slightly easier) solution might be to subclass your custom view's root layout (like, if it's a LinearLayout, make a SquareLinearLayout), and use that as a container instead.
edit : Here's a basic implementation which seems to work for me :
package com.mantano.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class SquareView extends ViewGroup {
public SquareView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onLayout(boolean changed, int l, int u, int r, int d) {
getChildAt(0).layout(0, 0, r-l, d-u); // Layout with max size
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
View child = getChildAt(0);
child.measure(widthMeasureSpec, widthMeasureSpec);
int width = resolveSize(child.getMeasuredWidth(), widthMeasureSpec);
child.measure(width, width); // 2nd pass with the correct size
setMeasuredDimension(width, width);
}
}
It's designed to have a unique child, but I ignored all of the checks for the sake of simplicity. The basic idea is to measure the child with the width/height parameters set by the GridView (in my case, it uses numColumns=4 to calculate the width), and then do a second pass with the final dimensions, with height=width...
The layout is just a plain layout, which layouts the unique child at (0, 0) with the desired dimensions (right-left, down-up).
And here's the XML used for the GridView items :
<?xml version="1.0" encoding="utf-8"?>
<com.mantano.widget.SquareView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<LinearLayout android:id="#+id/item" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal"
android:gravity="center">
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Hello world" />
</LinearLayout>
</com.mantano.widget.SquareView>
I used a LinearLayout inside the SquareView in order to have it manage all the gravity possibilities, margins, etc.
I'm not sure how well (or bad) this widget would react to orientation and dimension changes, but it seems to work correctly.
It ends up being fairly easy to get the grid item square.
In your "GetView" method of your grid adapter, just do:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GridView grid = (GridView)parent;
int size = grid.getRequestedColumnWidth();
TextView text = new TextView(getContext());
text.setLayoutParams(new GridView.LayoutParams(size, size));
// Whatever else you need to set on your view
return text;
}
I don`t know if it is the best way, but I accomplish that making my custom view to override onSizeChanged that way:
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (getLayoutParams() != null && w != h) {
getLayoutParams().height = w;
setLayoutParams(getLayoutParams());
}
}
I use this custom view inside a LinearLayout and a GridView and in both it is showing square!
Try
<GridView
...
android:stretchMode="columnWidth" />
You can also play with other modes
This worked for me!
If you are like me and you can't use getRequestedColumnWidth() because your minSdk is lower than 16, I suggest this option.
in your fragment:
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int size = dm.widthPixels / nbColumns;
CustomAdapter adapter = new CustomAdapter(list, size, getActivity());
in your adapter (in getView(int position, View convertView, ViewGroup parent))
v.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, size));
fragment.xml:
<GridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="3dp"
android:verticalSpacing="3dp"
android:numColumns="4"
android:stretchMode="columnWidth" />
custom_item.xml: (for example)
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
Hope it will help someone!
if you set a static number of columns in the xml then you can take the width of the view and divide it by the number of columns.
if you are using auto_fit then it's going to be a bit tricky to get the column count ( there is no getColumnCount() method ), btw this question should help you somehow.
this is the code I'm using into the getView(...) method of the adapter with a fixed number of columns:
item_side = mFragment.holder.grid.getWidth() / N_COL;
v.getLayoutParams().height = item_side;
v.getLayoutParams().width = item_side;
This is what I am doing to show square cells in a GridView. I am not sure if you want square cells or something else.
GridView grid = new GridView( this );
grid.setColumnWidth( UIScheme.cellSize );
grid.setVerticalSpacing( UIScheme.gap );
grid.setStretchMode( GridView.STRETCH_COLUMN_WIDTH );
grid.setNumColumns( GridView.AUTO_FIT );
And then the view which I am creating for each cell I have to do the following to it:
cell.setLayoutParams( new GridView.LayoutParams(iconSize, iconSize) );
Based on SteveBorkman's answer, which is API 16+:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GridView grid = (GridView)parent;
int size = grid.getColumnWidth();
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.your_item, null);
convertView.setLayoutParams(new GridView.LayoutParams(size, size));
}
//Modify your convertView here
return convertView;
}
Along the lines of #Gregory's answer, I had to wrap my image in a LinearLayout in order to keep GridView from manipulating its dimensions from square. Note that the outer LinearLayout should be set to have the dimension of the image, and the width of the GridView column should be the width of the image PLUS any margin. For example:
<!-- LinearLayout wrapper necessary to wrap image button in order to keep square;
otherwise, the grid view distorts it into rectangle.
also, margin top and right allows the indicator overlay to extend top and right.
NB: grid width is set in filter_icon_page.xml, and must correspond to size + margin
-->
<LinearLayout
android:id="#+id/sport_icon_lay"
android:layout_width="60dp"
android:layout_height="60dp"
android:orientation="vertical"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
>
<ImageButton
android:id="#+id/sport_icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:maxHeight="60dp"
android:maxWidth="60dp"
android:scaleType="fitCenter"
/>
</LinearLayout>
and the GridView like:
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:columnWidth="66dp"
android:numColumns="auto_fit"
android:verticalSpacing="25dp"
android:horizontalSpacing="24dp"
android:stretchMode="spacingWidth"
/>
In your activity
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
valX = displaymetrics.widthPixels/columns_number;
in the CustomAdapter of the GridView
v.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, YourActivity.valX));

Android: why is there no maxHeight for a View?

View's have a minHeight but somehow are lacking a maxHeight:
What I'm trying to achieve is having some items (views) filling up a ScrollView. When there are 1..3 items I want to display them directly. Meaning the ScrollView has the height of either 1, 2 or 3 items.
When there are 4 or more items I want the ScrollView to stop expanding (thus a maxHeight) and start providing scrolling.
However, there is unfortunately no way to set a maxHeight. So I probably have to set my ScrollView height programmatically to either WRAP_CONTENT when there are 1..3 items and set the height to 3*sizeOf(View) when there are 4 or more items.
Can anyone explain why there is no maxHeight provided, when there is already a minHeight?
(BTW: some views, like ImageView have a maxHeight implemented.)
None of these solutions worked for what I needed which was a ScrollView set to wrap_content but having a maxHeight so it would stop expanding after a certain point and start scrolling. I just simply overrode the onMeasure method in ScrollView.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(300, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
This might not work in all situations, but it certainly gives me the results needed for my layout. And it also addresses the comment by madhu.
If some layout present below the scrollview then this trick wont work – madhu Mar 5 at 4:36
In order to create a ScrollView or ListView with a maxHeight you just need to create a Transparent LinearLayout around it with a height of what you want the maxHeight to be. You then set the ScrollView's Height to wrap_content. This creates a ScrollView that appears to grow until its height is equal to the parent LinearLayout.
This worked for me to make it customizable in xml:
MaxHeightScrollView.java:
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
private final int defaultHeight = 200;
public MaxHeightScrollView(Context context) {
super(context);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
init(context, attrs);
}
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!isInEditMode()) {
init(context, attrs);
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (!isInEditMode()) {
init(context, attrs);
}
}
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
//200 is a defualt value
maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_maxHeight, defaultHeight);
styledAttrs.recycle();
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
attr.xml
<declare-styleable name="MaxHeightScrollView">
<attr name="maxHeight" format="dimension" />
</declare-styleable>
example layout
<blah.blah.MaxHeightScrollView android:layout_weight="1"
app:maxHeight="90dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText android:id="#+id/commentField"
android:hint="Say Something"
android:background="#FFFFFF"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:gravity="center_vertical"
android:maxLines="500"
android:minHeight="36dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</blah.blah.MaxHeightScrollView>
(I know this does not directly answer the question but might be helpful to others looking for maxHeight functionality)
ConstraintLayout offers maximum height for its children via
app:layout_constraintHeight_max="300dp"
app:layout_constrainedHeight="true"
or
app:layout_constraintWidth_max="300dp"
app:layout_constrainedWidth="true"
Sample usage here.
I would have commented on whizzle's answer if I could, but thought it useful to note that in order for me to solve this problem in the context of multi-window mode in Android N, I needed to change the code slightly to this:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(MeasureSpec.getSize(heightMeasureSpec) > maxHeight) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
This allows for the layout to resize to be smaller than the max height, but also prevent it from being larger than the max height. I used this is a layout class that Overrides RelativeLayout and this allowed me to create a custom dialog with a ScrollView as the child of MaxHeightRelativeLayout that does not expand the full height of the screen and also shrinks to fit within the smallest widow size in multi-window for Android N.
As mentioned above, ConstraintLayout offers maximum height for its children via:
app:layout_constraintHeight_max="300dp"
app:layout_constrainedHeight="true"
Besides, if maximum height for one ConstraintLayout's child is uncertain until App running, there still has a way to make this child automatically adapt a mutable height no matter where it was placed in the vertical chain.
For example, we need to show a bottom dialog with a mutable header TextView, a mutable ScrollView and a mutable footer TextView. The dialog's max height is 320dp,when total height not reach 320dp ScrollView act as wrap_content, when total height exceed ScrollView act as "maxHeight=320dp - header height - footer height".
We can achieve this just through xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="320dp">
<TextView
android:id="#+id/tv_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black_10"
android:gravity="center"
android:padding="10dp"
app:layout_constraintBottom_toTopOf="#id/scroll_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1"
app:layout_constraintVertical_chainStyle="packed"
tools:text="header" />
<ScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black_30"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toTopOf="#id/tv_footer"
app:layout_constraintHeight_max="300dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tv_header">
<LinearLayout
android:id="#+id/ll_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_sub1"
android:layout_width="match_parent"
android:layout_height="160dp"
android:gravity="center"
android:textColor="#color/orange_light"
tools:text="sub1" />
<TextView
android:id="#+id/tv_sub2"
android:layout_width="match_parent"
android:layout_height="160dp"
android:gravity="center"
android:textColor="#color/orange_light"
tools:text="sub2" />
</LinearLayout>
</ScrollView>
<TextView
android:id="#+id/tv_footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black_50"
android:gravity="center"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/scroll_view"
tools:text="footer" />
</android.support.constraint.ConstraintLayout>
Most import code is short:
app:layout_constraintVertical_bias="1"
app:layout_constraintVertical_chainStyle="packed"
app:layout_constrainedHeight="true"
Horizontal maxWidth usage is quite the same.
There is no way to set maxHeight. But you can set the Height.
To do that you will need to discovery the height of each item of you scrollView. After that just set your scrollView height to numberOfItens * heightOfItem.
To discovery the height of an item do that:
View item = adapter.getView(0, null, scrollView);
item.measure(0, 0);
int heightOfItem = item.getMeasuredHeight();
To set the height do that:
// if the scrollView already has a layoutParams:
scrollView.getLayoutParams().height = heightOfItem * numberOfItens;
// or
// if the layoutParams is null, then create a new one.
scrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, heightOfItem * numberOfItens));
Wrap your ScrollView around your a plainLinearLayout with layout_height="max_height", this will do a perfect job. In fact, I have this code in production from last 5 years with zero issues.
<LinearLayout
android:id="#+id/subsParent"
android:layout_width="match_parent"
android:layout_height="150dp"
android:gravity="bottom|center_horizontal"
android:orientation="vertical">
<ScrollView
android:id="#+id/subsScroll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp">
<TextView
android:id="#+id/subsTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/longText"
android:visibility="visible" />
</ScrollView>
</LinearLayout>
My MaxHeightScrollView custom view
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
public MaxHeightScrollView(Context context) {
this(context, null);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray styledAttrs =
context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
try {
maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_mhs_maxHeight, 0);
} finally {
styledAttrs.recycle();
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (maxHeight > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
style.xml
<declare-styleable name="MaxHeightScrollView">
<attr name="mhs_maxHeight" format="dimension" />
</declare-styleable>
Using
<....MaxHeightScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:mhs_maxHeight="100dp"
>
...
</....MaxHeightScrollView>
I have an answer here:
https://stackoverflow.com/a/29178364/1148784
Just create a new class extending ScrollView and override it's onMeasure method.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (maxHeight > 0){
int hSize = MeasureSpec.getSize(heightMeasureSpec);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
switch (hMode){
case MeasureSpec.AT_MOST:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.AT_MOST);
break;
case MeasureSpec.UNSPECIFIED:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
break;
case MeasureSpec.EXACTLY:
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.EXACTLY);
break;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
In case anyone needs it:
app:layout_constraintHeight_max="300dp"
It forces the View (that is inside a ConstraintLayout) to be 300dp as a max height. For those who want to do this programmatically, it goes like this:
val totalScreenHeight = displayMetrics.heightPixels
val layoutParams: ConstraintLayout.LayoutParams = viewThatIsInsideAConstraintLayout.layoutParams as ConstraintLayout.LayoutParams
layoutParams.matchConstraintMaxHeight = totalScreenHeight/2
viewThatIsInsideAConstraintLayout.layoutParams = layoutParams
Have you tried using the layout_weight value? If you set one it to a value greater than 0, it will stretch that view into the remaining space available.
If you had multiple views that needed to be stretched, then the value will become a weight between them.
So if you had two views both set to a layout_weight value of 1, then they would both stretch to fill in the space but they would both stretch to an equal amount of space. If you set one of them to the value of 2, then it would stretch twice as much as the other view.
Some more info here listed under Linear Layout.
i think u can set the heiht at runtime for 1 item just scrollView.setHeight(200px), for 2 items scrollView.setheight(400px) for 3 or more scrollView.setHeight(600px)
As we know devices running android can have different screen sizes. As we further know views should adjust dynamically and become the space which is appropriate.
If you set a max height you maybe force the view not to get enough space or take to less space. I know that sometimes it seems to be practically to set a max height. But if the resolution will ever change dramatically, and it will!, then the view, which has a max height, will look not appropriate.
i think there is no proper way to exactly do the layout you want. i would recommend you to think over your layout using layout managers and relative mechanisms. i don't know what you're trying to achieve but it sounds a little strange for me that a list should only show three items and then the user has to scroll.
btw. minHeight is not guaranteed (and maybe shouldn't exist either). it can have some benefit to force items to be visible while other relative items get smaller.
If anyone is considering using exact value for LayoutParams e.g.
setLayoutParams(new LayoutParams(Y, X );
Do remember to take into account the density of the device display otherwise you might get very odd behaviour on different devices. E.g:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics d = new DisplayMetrics();
display.getMetrics(d);
setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, (int)(50*d.density) ));
First get the item height in pixels
View rowItem = adapter.getView(0, null, scrollView);
rowItem.measure(0, 0);
int heightOfItem = rowItem.getMeasuredHeight();
then simply
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
scrollView.getLayoutParams().height = (int)((heightOfItem * 3)*displayMetrics .density);
if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/topview"
android:layout_below="#+id/bottomview" >
I used a custom ScrollView made in Kotlin which uses maxHeight. Example of use:
<com.antena3.atresplayer.tv.ui.widget.ScrollViewWithMaxHeight
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</com.antena3.atresplayer.tv.ui.widget.ScrollViewWithMaxHeight>
Here is the code of ScrollViewWidthMaxHeight:
import android.content.Context
import android.util.AttributeSet
import android.widget.ScrollView
import timber.log.Timber
class ScrollViewWithMaxHeight #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
companion object {
var WITHOUT_MAX_HEIGHT_VALUE = -1
}
private var maxHeight = WITHOUT_MAX_HEIGHT_VALUE
init {
val a = context.obtainStyledAttributes(
attrs, R.styleable.ScrollViewWithMaxHeight,
defStyleAttr, 0
)
try {
maxHeight = a.getDimension(
R.styleable.ScrollViewWithMaxHeight_android_maxHeight,
WITHOUT_MAX_HEIGHT_VALUE.toFloat()
).toInt()
} finally {
a.recycle()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightMeasure = heightMeasureSpec
try {
var heightSize = MeasureSpec.getSize(heightMeasureSpec)
if (maxHeight != WITHOUT_MAX_HEIGHT_VALUE) {
heightSize = maxHeight
heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST)
} else {
heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.UNSPECIFIED)
}
layoutParams.height = heightSize
} catch (e: Exception) {
Timber.e(e, "Error forcing height")
} finally {
super.onMeasure(widthMeasureSpec, heightMeasure)
}
}
fun setMaxHeight(maxHeight: Int) {
this.maxHeight = maxHeight
}
}
which needs also this declaration in values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ScrollViewWithMaxHeight">
<attr name="android:maxHeight" />
</declare-styleable>
</resources>

Categories

Resources