I created a custom View, and I put this on a LinearLayout.
Problem is that I cannot fill completely the height of the layout, the size of the custom View is always squared, width = height.
Here is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:layout_weight="0">
<it.inav.graphics.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"/>
</LinearLayout>
The only way it seems to work is using a RelativeLayout and "strecth" the view using both
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
but still, if I try to get the size height, it returns the same length of before.
The problem was in the definition of the View, and not in the XML.
I have done copy-paste of this piece of code:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = measure(widthMeasureSpec);
int measuredHeight = measure(heightMeasureSpec);
int d = Math.min(measuredWidth, measuredHeight);
setMeasuredDimension(d, d);
}
And, naturally, it sets the size of the View as a square with the length of the minor.
This is the correct code:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = measure(widthMeasureSpec);
int measuredHeight = measure(heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
Related
I believe my problem is related to this: widthMeasureSpec is 0 when in HorizontalScrollView
Long story short, I'm trying to create a custom horizontal scroll view. At some point, I'm overriding
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
And while this works fine in Android >= 7, I'm getting a value of 0 for widthMeasureSpec in Android <= 6.
The code for measureChild changed between API 23 and 24:
In API 23:
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
In API 24:
final int childWidthMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentWidthMeasureSpec) - horizontalPadding),
MeasureSpec.UNSPECIFIED);
I have tried to get the width from the parent view using a getter, but it is not working as expected as only some calls get the correct width. I also tried to override measureChild in the parent and putting the newest code there, with no luck:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChild(getTouchInterceptTextView(), widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
ViewGroup.LayoutParams lp = child.getLayoutParams();
final int horizontalPadding = getPaddingLeft() + getPaddingRight();
final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentWidthMeasureSpec) - horizontalPadding),
MeasureSpec.UNSPECIFIED);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
getPaddingTop() + getPaddingBottom(), lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
My wholes files are here: https://github.com/AdrienPoupa/VinylMusicPlayer/commit/ba0dfae7dd03771f3625b8393927986aad552e2a
The important part being:
<com.poupa.vinylmusicplayer.views.TouchInterceptHorizontalScrollView
android:id="#+id/title_scrollview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.poupa.vinylmusicplayer.views.AutoTruncateTextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="#style/TextAppearance.AppCompat.Subhead" />
</com.poupa.vinylmusicplayer.views.TouchInterceptHorizontalScrollView>
The onMeasure function is in AutoTruncateTextView. I can get the measures in TouchInterceptHorizontalScrollView but that does not seem to help. I tried to add android:fillViewport="true" in the XML for TouchInterceptHorizontalScrollView, AutoTruncateTextView and both but it did not change the calculation.
What can I do to get the proper value of widthMeasureSpec in Android 6 and below?
Thanks for your help!
After many tries, it seems to be working by adding the following snippet to AutoTruncateTextView's onMeasure:
if (textBoundsWidth == 0) {
textBoundsWidth = getTouchInterceptFrameLayout().getMeasuredWidth();
}
Basically, getting the width of the TouchInterceptFrameLayout, that is the 2nd level of the XML file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="72dp"
android:foreground="?attr/rectSelector"
tools:ignore="UnusedAttribute">
<!-- for getSwipeableContainerView() -->
<com.poupa.vinylmusicplayer.views.TouchInterceptFrameLayout
android:id="#+id/dummy_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
and keeping the code posted above otherwise the truncate mechanism does not work anymore.
I am trying to create own custom view ,I observed onMeasure shows into 2 of whatever value set.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.customview.PercentageCircle
android:layout_width="match_parent"
android:layout_height="100dp"
custom:currentValue="0"
custom:maxValue="100"
custom:thickNess="80"
custom:fillBackgroundColor="#color/light_gray"
custom:fillColor="#color/red"
/>
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);//shows 200
this.setMeasuredDimension(parentWidth, parentHeight);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
When I log the parentHeight or parentWidth ,I get double the specified value.I am not able to understand cause of it.
All the inputs to Canvas functions are in pixels.
Function parameters of onMeasure are also in pixels.
To work UI across the devices , If we use pixels, things become too small on high resolution screens.
To convert from dp to pixels,
float heightInPixel = getHeight()/ getResources().getDisplayMetrics().density;
I would like to have a square (same width as height) GridView fill the full height of the screen in landscape orientation. The Gridview is a chessboard (8 by 8 squares) with the xml:
<com.example.jens.jchess2.view.MyGridView
android:id="#+id/chessboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp"
android:numColumns="8"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp">
</com.example.jens.jchess2.view.MyGridView>
and the elements of the grid are:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/square"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000080"
android:orientation="vertical"
android:padding="0pt">
<ImageView
android:id="#+id/square_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:padding="0pt" />
<ImageView
android:id="#+id/piece"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:padding="0pt" />
</FrameLayout>
, where the ImageViews correspond to the squares and pieces (both from png images) of the board.
In the custom MyGridView I override onMeasure as follows:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = getContext().getResources().getDisplayMetrics().heightPixels;
if (width > height) {
super.onMeasure(
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
);
} else {
super.onMeasure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)
);
}
}
which gives me a square GridView in both portrait and landscape orientation. In portrait mode it fills the full width and everything is fine. In landscape mode however it extends below the screen because the height (=width) of the GridView/board is too large. It is too large by the height of the toolbar and the height of the statusbar. How can I get the proper size for the GridView, i.e. screen height minus status bar height minus toolbar height?
Start with two versions of your layout file:
/res/layout/grid.xml
...
<!-- full width -->
<com.example.MyGridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
/>
...
/res/layout-land/grid.xml
...
<!-- full height -->
<com.example.MyGridView
android:layout_width="wrap_content"
android:layout_height="match_parent"
...
/>
...
You probably already have something like this.
Now in your onMeasure() override, the match_parent dimension will have a MeasureSpec mode of EXACTLY and the wrap_content dimension will have a MeasureSpec mode of AT_MOST. You can use this to achieve your desired layout.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.AT_MOST) {
// portrait
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
} else if (heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.AT_MOST) {
// landscape
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
EDIT: I found out that both modes can be AT_MOST depending on the ViewGroup container. Please see my other answer for updated measuring code.
Ah. Now I see that this is for a game.
Sometimes it's better to have layouts and child views, but in most cases with game boards you are better off creating a single View subclass that represents the game view.
For instance, what if your users say they want the ability to pinch-zoom into one quadrant of the game board? You can't do that with a GridView.
I whipped up a simple app to show you how this can work. I simplified the onMeasure() code I posted before, and instead of a GridView, a single View subclass renders the game board.
The MainActivity simply sets up the content view.
/res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gameboard.MainActivity">
<com.example.gameboard.GameBoardView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
/res/layout-land/activity_main.xml:
Notice match_parent and wrap_content are switched for width and height.
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gameboard.MainActivity">
<com.example.gameboard.GameBoardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
</RelativeLayout>
GameBoardView.java:
public class GameBoardView extends View {
private Paint mPaint;
public GameBoardView(Context context) {
super(context);
}
public GameBoardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GameBoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public GameBoardView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = Math.min(width, height);
int sizeMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(sizeMeasureSpec, sizeMeasureSpec);
mPaint = new Paint();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth() / 8;
int h = getHeight() / 8;
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
// choose black or white depending on the square
mPaint.setColor((row + col) % 2 == 0 ? 0xFFFFFFFF : 0xFF000000);
canvas.drawRect(w * col, h * row, w * (col + 1), h * (row + 1), mPaint);
}
}
}
}
Here I'm just drawing the squares right in the view. Now, if I were making a chess game, I would also create a Drawable subclass that would take the game model and render it. Having a separate Drawable for rendering the game makes it easy to scale to the correct size. For example, your Drawable could render at a fixed constant size, then be scaled by the View subclass to fit. The View subclass would function mostly as a controller, interpreting touch events and updating the game model.
I create my own class for the square layout:
public class SquareLayout extends LinearLayout{
public SquareLayout(Context context) {
super(context);
}
public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}
Then, in my xml:
...
<com.myApp.SquareLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >
<ImageView
android:id="#+id/cellImageView"
android:adjustViewBounds="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:padding="2dp"
android:scaleType="centerCrop"
android:src="#drawable/image" />
</com.myApp.SquareLayout>
...
Nothing written more in my java code.
But instead if my layout and my Image, I see only a white rectangle...
What am I wrong?
// you forget to call super.onMeasure(widthMeasureSpec, widthMeasureSpec);
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}
// xml file
<com.example.testapplication.SquareLayout
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >
<ImageView
android:id="#+id/cellImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:adjustViewBounds="true"
android:padding="2dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_launcher" />
</com.example.testapplication.SquareLayout>
I had problems calling setMeasuredDimension directly when applying the same technique to a RelativeLayout. I was unable to correctly align against the bottom edge. Changing to instead call up to super.onMeasure() with a new measure spec worked better.
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = Math.min(width, height);
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}
Edit:
The solution below has now been deprecated, as ConstraintLayout has become the new standard and provides this functionality.
Original Answer:
Turns out the Android team gave us the solution, but nobody knows about it! Check out these two classes from the Percent Support Library:
PercentFrameLayout
PercentRelativeLayout
If you want to impose the ratio of a view, you have to place it within one of these layouts. So in this case, you have to place a standard LinearLayout, not your subclass, within one of these layouts with the right aspect ratio. Example if you want to use a PercentFrameLayout:
<android.support.percent.PercentFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_aspectRatio="100%">
<!-- Whatever subviews you want here -->
</LinearLayout>
</android.support.percent.PercentFrameLayout>
And there you go, all your views will be contained within a square linear
layout!
don't forget to add the gradle dependency compile 'com.android.support:percent:23.3.0' Adjust the version number as required
what I want to do in a view is have a textview and to the right of it, have another custom view X with the same height as the textview and have width=height:
+---------------------+---+
|A flexible string | X |
+---------------------+---+
My attempt so far is:
Inside the X class:
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(height,height);
Log.v("measure","width:"+height + " height:"+height);
}
and my xml:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="#+id/mytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"/>
<mystuff.X
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#id/mytext"/>
</RelativeLayout>
The log statement prints out:
width:1073741823 height:1073741823
width:37 height:37
width:1073741823 height:1073741823
width:37 height:37
width:1073741823 height:1073741823
width:37 height:37
when the view is created and it fills the width of the screen:
+---------------------+-----------------+
|A flexible string | X |
+---------------------+-----------------+
I would greatly appreciate any help with this.
Thanks!
Ian
You are treating the measure specs as actual pixels. They are in fact the ints that represent "fill_parent", "wrap_content", etc.
What you want to do is:
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(height,height);
Log.v("measure","width:"+height + " height:"+height);
}