How to force GridView to generate square cells in Android - android

How can I force an android GridView to generate square cells (Cell's height equal to cell's width)
GridView has 10*9 cells and the app must support multiple screens !
I used a Linear Layout:
row_grid.xml
<LinearLayout 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:padding="0dp" >
<ImageView
android:id="#+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" >
</ImageView>
</LinearLayout>
and GridView:
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"
android:background="#drawable/katy" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="0dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp" >
</GridView>
</RelativeLayout>
Each cell of GridView contains a image that has same width and height.
images are larger than cells and must stretch to fit in cells.

First, you're going to want to create a custom View class that you can use instead of the default LinearLayout you're using. Then you want to override the View's onMeasure call, and force it to be square:
public class GridViewItem extends ImageView {
public GridViewItem(Context context) {
super(context);
}
public GridViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
}
}
Then you can change your row_grid.xml file to:
<path.to.item.GridViewItem xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/ic_launcher" >
</path.to.item.GridViewItem>
Just be sure to change "path.to.item" to the package where your GridViewItem.java class resides.
I also removed your LinearLayout parent since it wasn't doing anything for you there.
Edit:
Also changed scaleType from fitXY to centerCrop so that your image doesn't stretch itself and maintains its aspect ratio. And, as long as it's a square image, nothing should be cropped, regardless.

You can Override your linear layout
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
}
}
then use it in the item_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/item_grid"
android:layout_margin="2dp"
android:padding="3dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category Name"
android:textStyle="bold"
android:textColor="#color/colorPrimary"
android:id="#+id/tvCategoryName" />
</com.example.MyLinearLayout>

How about using ConstraintLayout?
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:gravity="center"
android:padding="3dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Works nicely, thank you! A small improvement I required would be always pick the smaller value, to prevent overshooting the screen:
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(heightMeasureSpec < widthMeasureSpec) {
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
} else if(widthMeasureSpec < heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class GridViewItem extends RelativeLayout {
public GridViewItem(Context context) {
super(context);
}
public GridViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
}
}
If your grid item just have an image then the answer is very good. But you want to add multiple items in your grid item then you must create Your Custom GridViewItem extending the layout you want your grid item to be. For example in my case I had RelativeLayout as the parent view so I created GridViewItem extending the RelativeLayout and it worked flawlessly.

Just make sure that your images are square. And make the container wrap_content.

Related

ListView inside ScrollView makes adapter call multiple times

Here is the sample code,
contact.xml
<ScrollView
android:id="#+id/scroll_view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:layout_marginBottom="55dp">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
style="#style/ContentFrame"
android:layout_marginTop="20dp"
android:layout_marginBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/msg_listview_frame"
android:layout_marginTop="10dp">
<com.android.bundle.helper.NonScrollListView
android:id="#+id/contact_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/white_lilac"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:scrollbars="none">
</com.android.bundle.helper.NonScrollListView>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
To make ListView non-scrollable, I'm using this custom class NonScrollListView.
NonScrollListView.java
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
The adapter is been called more than 40 times, I have tried a couple of options from StackOverflow like changing listview height = fill_parent as well as match_parent.
I know this is an old issue, I'm new to android not able to resolve this one. Kindly help to resolve this issue.
Note: At any cost, ListView has to be inside ScrollView. I want to make CardView be scrollable.
Thanks

Image in layout is not the correct size

This is how it looks:
I've added an image to my layout. Because the image was a big small, and ended up in the middle of my screen, not filling the entire width of the screen, i had to stretch it out. With that, the letters obviously stretch out as well, which makes it look bad. I know that this might be unfixable. Every image needs to be stretched out, so the colors are fine, but the letters are always a bit hazy after that.
If this has no solutions at all, just tell me so I know that. If you think you know how to fix this, please help.
Don't think it's relevant, but this is the code that i added the image with:
<LinearLayout 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:orientation="vertical"
tools:context="com.example.rodekruis.MainActivity">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="#drawable/rkz_logo4"
android:layout_marginBottom="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"
/>
Try to remove the attributes android: scaleType = "fitXY" and replace the android: layout_width = "fill_parent" on android: layout_width = "wrap_content"
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/rkz_logo4"
android:layout_marginBottom="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
Create MyImageView.class
public class MyImageView extends ImageView {
public final static int WIDTH_IMAGE = 640;
public final static int HEIGHT_IMAGE = 200;
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * HEIGHT_IMAGE / WIDTH_IMAGE;
setMeasuredDimension(width, height);
}
}
in xml
<?xml version="1.0" encoding="utf-8"?>
<your.package.MyImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image_banner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/rkz_logo4"
android:layout_marginBottom="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>

centering child items in gridview

I am trying to populate a gridview with image thumbnails. I am unable to center the child items and a mismatch occurs when the image orientation is different i.e landscape vs portrait. The pic shows how it is coming out. I dont want to change the size of the thumbnails but to display the text view on the same level and the imageview to be centered accordingly.
photo gridview with childs not centered
Gridview XML:
<syook.syookfirst.classes.Utils.ExpandableHeightGridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview_call_photos"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:nestedScrollingEnabled="true"
android:gravity="center"
android:layout_gravity="center"
android:numColumns="auto_fit">
</syook.syookfirst.classes.Utils.ExpandableHeightGridView>
ExpandableHeightGridView class:
public class ExpandableHeightGridView extends GridView
{
boolean expanded = false;
public ExpandableHeightGridView(Context context)
{
super(context);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public boolean isExpanded()
{
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded)
{
this.expanded = expanded;
}
}
Gridview child layout:
<?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="vertical"
android:background="#drawable/button_pressed_nocolor_all"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/photo_thumb_calldetails"
android:padding="5dp"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/label_photo_name"
android:textSize="12sp"
android:layout_gravity="center"
android:gravity="center"
android:padding="2dp"
android:layout_marginBottom="2dp" />
Appreciate any help on this. I tried searching for such issues but haven't been able to resolve it with any of the solutions provided.
Setting the height of ImageView to 100dp works. Thanks :)
Just set fix width and set gravity to center.
android:layout_width="8" and
android:gravity="center"

Combining layout_weight and maxHeight

I'm quite new to Android programming and I'm stuck on an simple problem.
I have a basic homepage with some buttons and a logo. I use a LinearLayout and the layout_weight attribute to distribute all the components.
Here is my code :
<LinearLayout 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"
android:orientation="vertical"
tools:context="iut.project.findmeapp.MainActivity" >
<ImageView
android:id="#+id/activityMainAppLogoIv"
android:layout_width="match_parent"
android:layout_height="#dimen/null_height"
android:contentDescription="#string/description_logo"
android:layout_weight="1"
android:maxHeight="#dimen/img_maxHeight"
android:layout_margin="#dimen/img_margin"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/activityMainMyEventsBtn"
android:layout_width="match_parent"
android:layout_height="#dimen/null_height"
android:layout_marginTop="#dimen/button_margin_vertical"
android:layout_marginBottom="#dimen/button_margin_vertical"
android:layout_weight="1"
android:text="#string/my_events" />
<Button
android:id="#+id/activityMainMyContactsBtn"
android:layout_width="match_parent"
android:layout_height="#dimen/null_height"
android:layout_marginTop="#dimen/button_margin_vertical"
android:layout_marginBottom="#dimen/button_margin_vertical"
android:layout_weight="1"
android:text="#string/my_contacts" />
<Button
android:id="#+id/activityMainLastNotifBtn"
android:layout_width="match_parent"
android:layout_height="#dimen/null_height"
android:layout_marginTop="#dimen/button_margin_vertical"
android:layout_marginBottom="#dimen/button_margin_vertical"
android:layout_weight="1"
android:text="#string/last_notification" />
<TextView
android:id="#+id/activityMainCopyrightTv"
android:layout_width="match_parent"
android:layout_height="#dimen/null_height"
android:gravity="center"
android:layout_weight="0.5"
android:layout_margin="#dimen/tw_margin"
android:text="#string/copyright" />
</LinearLayout>
(Note : #dimen/null_height is 0dp)
My problem is that I want the image to scale with the size of the screen, but I don't want it pixelated : I have set a maximum height of 200px.
The following lines don't seem to work, because the image has no limit and totally ignores the maxHeight attribute.
android:layout_weight="1"
android:maxHeight="#dimen/img_maxHeight"
Actually it looks like this (example image) :
It works perfectly, but when I set maxHeight to 10px for example, nothing changes.
How can I achieve this ? I highly prefer to use a LinearLayout.
Thank you in advance.
Thanks to Evripidis Drakos for pointing me in the right direction. Just need a check to only set the max height if it's actually required.
public class MaxHeightImageView extends ImageView {
public static final int MAX_HEIGHT_NOT_SET = -1;
public static final int INDEX_MAX_HEIGHT = 0;
private static final int[] STYLE_ATTRIBUTE_ARRAY = {
android.R.attr.maxHeight,
};
private int myMaxHeight;
public MaxHeightImageView(Context context) {
super(context);
init(context, null);
}
public MaxHeightImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public MaxHeightImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MaxHeightImageView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int size = MeasureSpec.getSize(heightMeasureSpec);
if(MAX_HEIGHT_NOT_SET != myMaxHeight && size > myMaxHeight) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(myMaxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void init(Context context, AttributeSet attrs) {
if(context != null) {
TypedArray ta = context.obtainStyledAttributes(attrs,
STYLE_ATTRIBUTE_ARRAY);
myMaxHeight = ta.getDimensionPixelSize(INDEX_MAX_HEIGHT, 0);
} else {
myMaxHeight = MAX_HEIGHT_NOT_SET;
}
}
}
I dont think that you can combine layout_weight with maxHeight.
You could try subclassing ImageView to override the onMeasure method like so:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
if u want to set exact height for your image u should use weightSum property with weight
edit:
for fixed height do not give weight for imageview just take parent layout for imageview then add weight for that linear layout(parent layout) and for imageview give height as wrap content and maxHeight. when u use weight with height="0dp" the content will capture the whole height so it will ignore maxHeight.
try this
<LinearLayout 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:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:weightSum="5"
tools:context="iut.project.findmeapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/activityMainAppLogoIv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="#string/quantity_hint"
android:maxHeight="200px"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<Button
android:id="#+id/activityMainMyEventsBtn"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="my_events" />
<Button
android:id="#+id/activityMainMyContactsBtn"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="my_contacts" />
<Button
android:id="#+id/activityMainLastNotifBtn"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="last_notification" />
<TextView
android:id="#+id/activityMainCopyrightTv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".5"
android:gravity="center"
android:text="copyright" />
</LinearLayout>

TextView doesn't show in custom ScrollView

I try to create custom ScrollView, which will have attribute max_height, but i faced with problem. When I set custom height, ScrollView doesn't show TextView.
Lite version of my code:
Layout:
<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">
<com.example.scrollviewtest.ExpandScrollView
android:id="#+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#Fe6" >
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView TextView TextView TextView TextView" />
</com.example.scrollviewtest.ExpandScrollView>
ExpandScrollView.java
public class ExpandScrollView extends ScrollView {
public ExpandScrollView(Context context) {
super(context);
}
public ExpandScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(widthSize, 180);
}}
So what do i do wrong?
Just remove the onMeasure() method in ExpandScrollView class. It is causing problem.
Once you remove it textview will be visible.
The problem was solved!
I just added super.onMeasure(widthMeasureSpec, heightMeasureSpec); before widthSize

Categories

Resources