Center GridView horizontally [duplicate] - android

This question already has answers here:
Android: center gridview horizontally
(4 answers)
Closed 9 years ago.
I have a GridView with 4 items that are added dynamically. I can center them vertically but can not horizontally. Tried everything...
Main.xml
...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center" >
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="spacingWidthUniform"
android:gravity="center"
android:listSelector="#drawable/card_button" >
</GridView>
</LinearLayout>
...
Items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="vertical"
android:gravity="center" >
<ImageButton
android:id="#+id/menuItem_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/light"
android:contentDescription="#string/item"
android:background="#00000000"
android:tint="#222222"
android:paddingTop="8dp"
android:paddingBottom="4dp" />
<TextView
android:id="#+id/menuItem_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#222222"
android:paddingBottom="8dp"
android:text="#string/item"
android:textSize="18sp"
android:singleLine="true" />
</LinearLayout>
I don't want to have fixed number of columns so android:numColumns="auto_fit" must stay.

I find out that it's not possible to center GridView horizontally with .xml
So I had to do it programmatically... This answer helped me a lot: https://stackoverflow.com/questions/6141910/android-center-gridview-horizontally
I had to make some changes to make it work:
GridView Adapter.java:
public Adapter(Context context, int width, int height, float density, GridView grid) {
this.context = context;
width_ = width; //get metrics.widthPixels from MainActivtiy.java
height_ = height; //get metrics.heightPixels from MainActivtiy.java
density_ = density; //get metrics.scaledDensity from MainActivtiy.java
grid_ = grid; //get GridView
Rect p = new Rect();
grid_.getSelector().getPadding(p);
int selectorPadding = p.left + p.right;
int mSizePx = (int) Math.floor(90 * density_); //90 is my column width
int mSpacingPx = (int) Math.floor(10 * density_); //10 is space between columns
int numColumns = (int) Math.floor(1f * (width_ - selectorPadding + mSpacingPx) / (mSizePx + mSpacingPx));
// CHANGES
int numbOfCol = menuValues.length; //menuValues (Array[]) are items you are adding to GridView
int contentWidth = 0;
//the most important part
if (numColumns > numbOfCol) {
contentWidth = numbOfCol * mSizePx;
contentWidth += (numbOfCol - 1) * mSpacingPx;
contentWidth += selectorPadding;
} else {
contentWidth = numColumns * mSizePx;
contentWidth += (numColumns - 1) * mSpacingPx;
contentWidth += selectorPadding;
}
int slack = width_ - contentWidth;
//
grid_.setNumColumns(numColumns); //set calculated number of collumns
grid_.setColumnWidth(mSizePx); //90
grid_.setVerticalSpacing(mSpacingPx); //10
grid_.setHorizontalSpacing(mSpacingPx); //10
//changed
grid_.setPadding(slack / 2, mSpacingPx, slack / 2, mSpacingPx); //I set top and bottom padding to 10dp (mSpacingPx)
}
Main.xml (changed):
...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center" >
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchMode="none"
android:gravity="center"
android:listSelector="#drawable/card_button"
android:drawSelectorOnTop="true" >
</GridView>
</LinearLayout>
...

Related

Kotlin how to display images in TableLayout

I am trying to display images in TableLayout. The images got displayed, but not as many rows and columns it should be (6 rows and 4 columns - see image below!).
This is what I tried
private fun drawGrid()
{
var row: TableRow
val cellSize: Size = getCellSize();
val layoutpParams: ViewGroup.LayoutParams = ViewGroup.LayoutParams(cellSize.width, cellSize.height)
var imageView: ImageView
_gridElementList = getData()
var index: Int = 0
for (i: Int in 0 until settings.row)
{
row = TableRow(this)
row.layoutParams = layoutpParams
for (j: Int in 0 until settings.column)
{
imageView = ImageView(this);
imageView.setImageResource(_gridElementList[index].drawableId)
row.addView(imageView);
index++
}
tableLayout.addView(row);
}
}
private fun getCellSize() : Size
{
windowManager.defaultDisplay.getMetrics(displaymetrics);
val screenHeight = displaymetrics.heightPixels
val screenWidth = displaymetrics.widthPixels
val height: Int = ( screenHeight / settings!!.row).toInt()
val width: Int = (screenWidth / settings!!.column).toInt()
return Size(width, height)
}
I need to fit the image size to always fit the screen. The matrix is min 2x2 and the max size can be 4 x 8.
The xmls for the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GameActivity">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/timeLabelTextView"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Eltelt idő"
android:textAlignment="center"
android:textSize="24sp" />
<TextView
android:id="#+id/timeTextView"
android:layout_width="168dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="0"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</LinearLayout>

How to set GridView row height?

I have a GridView, and setting the number of columns and the overal width of the grid layout. Need items with 66dp x 66dp size. But somehow items are squared, but smaller the 66x66. What am I forget?
int zz = .. // number of columns comes from outside
gridview.setNumColumns(zz);
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)gridview.getLayoutParams();
linearParams.width=66*zz;
gridview.setLayoutParams(linearParams);
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:columnWidth="66dp"
android:gravity="center"
android:horizontalSpacing="0dp"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal"
android:stretchMode="none"
android:verticalSpacing="0dp">
</GridView>
item prototype
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="66dp" android:layout_height="66dp">
<ImageView
android:id="#+id/icon"
android:layout_width="66dp"
android:layout_height="66dp"
android:padding="0dp"
android:background="#android:color/holo_orange_light"/>
</RelativeLayout>
shreen shot
You can Use This..
int width = 66*zz;
view.setLayoutParams(new GridView.LayoutParams(GridView.width, YOUR_HEIGHT));
LinearLayout.LayoutParams require value in pixel not dp
int gridItemWithInDp = 66;
int gridItemWithInPx = (int) (gridItemWithInDp * Resources.getSystem().getDisplayMetrics().density);
linearParams.width=gridItemWithInPx *zz;
gridview.setLayoutParams(linearParams);
You should set the width of gridview in dp either from code or from declared into resource xml
from code:
final float density = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) ((66 * zz) * density + 0.5f);
or from xml
int pixels = getResources().getDimensionPixelSize(R.dimen.example_dimen);
gridview.setNumColumns(zz);
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)gridview.getLayoutParams();
linearParams.width=pixels;
gridview.setLayoutParams(linearParams);
Set item prototype width and height MATCH_PARENT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/icon"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp"
android:background="#android:color/holo_orange_light"/>
</RelativeLayout>

How to set weight for width and height?

I need to create view dynamical with width and height which are the percent of parent size.So I need to add weight for width and height for one view.
Is it possible?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:weightSum="4"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_weight="1"
android:gravity="center"
android:id="#+id/imgtype"
android:scaleType="fitCenter"/>
<TextView
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_weight="3"
android:id="#+id/txtsubject"
android:textStyle="bold"
android:textSize="#dimen/lat_sub_text_size"
android:textColor="#android:color/black"/>
<LinearLayout/>
here you will be able to divide the major portion of parent linearlayout's width to the textview and remaining minor part for imageview this is for aligning horizontally the same can be done for vertical as well.Weightsum property of parent decides number of parts it will contain.
For example, I have the below layout:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/ll_forImage"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll_forList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</LinearLayout>
Now, I will set width and height for each View depend on Screen width and Screen Height.
int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
int screenHeight = dpToPx(getResources().getConfiguration().screenHeightDp);
int ratioW = ....;//
int ratioH = ....;//
setLayoutSize(ll_forImage, screenWidth/ratioW , screenHeight/ratioH );
setLayoutSize(ll_forList, screenWidth/ratioW , screenHeight - screenHeight/ratioH );
// You can use setTranslation to translate View to expected position.
with:
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
private static void setLayoutSize(View view, int width, int height) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
Adding layout_weight is a good approach while using LinearLayout.
Remember, layout_weight works only in case of LinearLayout and cannot be used with RelativeLayout.

Position children views relative to their parent view

I need to implement a view that looks like this
The hard part is that the sizes and the font sizes of the textviews need to be adaptable to the width and height of the parent view. Here is what I have tried and the result is
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:layout_width="200dp"
tools:layout_height="100dp"
android:orientation="vertical">
<BuySellView
android:id="#+id/tradeNow_layoutSell"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#color/gray_light_light">
<LinearLayout
android:id="#+id/smallPart1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|right"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<ImageView
android:id="#+id/greenArrowSellImg"
android:layout_width="10dp"
android:layout_height="10dp"
android:src="#drawable/green_arrow"
android:visibility="invisible"
tools:visibility="visible" />
<ImageView
android:id="#+id/redArrowSellImg"
android:layout_width="10dp"
android:layout_height="10dp"
android:src="#drawable/red_arrow"
android:visibility="invisible"
tools:visibility="visible" />
</RelativeLayout>
<TextView
android:id="#+id/smallPart1Txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="top|right"
android:layout_gravity="center_vertical"
android:maxLines="1"
android:text="#string/misc_blank"
android:textColor="#android:color/black"
tools:text="10,015." />
</LinearLayout>
<TextView
android:id="#+id/largePart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines="1"
android:text="#string/misc_blank"
android:textColor="#android:color/black"
tools:text="46"
android:gravity="center"
tools:textColor="#color/red_sell" />
<TextView
android:id="#+id/smallPart2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:maxLines="1"
android:text="#string/misc_blank"
android:textColor="#android:color/black"
android:gravity="left|center_vertical"
tools:text="8"
tools:textColor="#color/red_sell" />
<TextView
android:id="#+id/trdLbl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#drawable/rounded_corner_sell"
android:text="#string/CommonCapitalSell"
android:textColor="#color/white" />
</BuySellView>
</LinearLayout>
The custom view:
public class BuySellView extends ViewGroup {
private final Rect mTmpChildRect = new Rect();
public BuySellView(Context context) {
super(context);
}
public BuySellView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BuySellView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int t = 10;
int b = 10 + height / 3 * 2;
LinearLayout smallPart1 = (LinearLayout) findViewById(R.id.smallPart1);
smallPart1.layout(0, height / 3, width / 2, b);
smallPart1.setGravity(Gravity.RIGHT);
TextView smallPart1Txt = (TextView) smallPart1.findViewById(R.id.smallPart1Txt);
smallPart1Txt.setTextSize(height / 4 / 2);
TextView largePart = (TextView) findViewById(R.id.largePart);
largePart.setTextSize(height / 3);
largePart.layout(width / 2, 10, b - t + width / 2, b);
TextView smallPart2 = (TextView) findViewById(R.id.smallPart2);
smallPart2.layout(b - t + width / 2, t, width, height / 2);
smallPart2.setTextSize(height / 4 / 2);
TextView tradeLbl = (TextView) findViewById(R.id.trdLbl);
tradeLbl.layout(width / 2 - width / 3 / 2, height / 4 * 3 + 10, width / 2 + width / 3 / 2, height / 4 * 4 + 10);
tradeLbl.setGravity(Gravity.CENTER);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
LinearLayout smallPart1 = (LinearLayout) findViewById(R.id.smallPart1);
TextView largePart = (TextView) findViewById(R.id.largePart);
TextView smallPart2 = (TextView) findViewById(R.id.smallPart2);
TextView tradeLbl = (TextView) findViewById(R.id.trdLbl);
smallPart1.measure(Math.max(smallPart1.getMeasuredWidth(), widthMeasureSpec / 8 * 3), heightMeasureSpec / 4);
largePart.measure(heightMeasureSpec / 4 * 2, heightMeasureSpec / 4 * 2);
smallPart2.measure(Math.max(smallPart2.getMeasuredWidth(), widthMeasureSpec / 8), smallPart2.getMeasuredHeight());
tradeLbl.measure(widthMeasureSpec / 3, heightMeasureSpec / 4);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
#Override
public boolean shouldDelayChildPressedState() {
return false;
}
}
try this XML:
<RelativeLayout
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.87"
android:textSize="25sp"
android:layout_alignBottom="#+id/large"
android:paddingBottom="8dp"
android:fontFamily="sans-serif-light"
/>
<TextView
android:id="#+id/large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/small"
android:text="46"
android:textSize="58sp"
android:textColor="#00DC00"
android:fontFamily="sans-serif-light"
/>
<TextView
android:id="#+id/up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:textSize="24sp"
android:layout_alignTop="#+id/large"
android:layout_toRightOf="#+id/large"
android:textColor="#00DC00"
android:fontFamily="sans-serif-light"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#FF4848"
android:layout_below="#+id/large"
android:layout_alignRight="#+id/large"
android:text="Sell USD"
android:padding="5dp"
android:textColor="#fff"
android:textSize="12sp"
/>
</RelativeLayout>
You can change the textSize based on number of character or width of text via java code.

RelativeLayout like TableLayout

Hi a have RelativeLayout and want display 6 buttons like a "TableLayout", i calc size buttons and tried display on Activity. Only last button appear.
I trying do Activity with 6 buttons (buttonsperscreen = 6) when call method.
Can you help me?
The code is:
private void doLayoutWithButtons(int buttonsperscreen) {
// if total butons is % 2 == 0
if (buttonsperscreen % 2 == 0) {
// get display dimensions
DisplayMetrics d = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(d);
int w = d.widthPixels;
int h = d.heightPixels;
// calc size of buttons
int widthButton = w / 2; // only two columns of buttons.
int heightButton = h / ((buttonsperscreen) / 2); // sample 100px /
// (6/2) = 3
int posx = 0;
int posy = 0;
for (int i = 1; i <= buttonsperscreen; i++) {
Button newButton = new Button(this);
newButton.setId(100 + i + 1); // ID of zero will not work
newButton.setText("Botão: " + i);
// atribuindo o tamanho do botão.
newButton.setHeight(heightButton);
newButton.setWidth(widthButton);
newButton.setId(1000 + i);
// positioning buttons...
RelativeLayout layout1 = new RelativeLayout(this);
// set layout with size of button
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
widthButton, heightButton);
params.leftMargin = posx;
params.topMargin = posy;
newButton.setLayoutParams(params);
layout1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout1.addView(newButton);
setContentView(layout1);
// to calc positions x,y for each button for next iteration
if (posx + widthButton < w) {
posx = posx + widthButton;
} else {
posx = 0;
posy = posy + heightButton;
}
}
}
}
Thanks
Mateus
If you're trying to display buttons evenly spaced across a screen, you don't need to do this in code. You can specify things like this in a layout.
Something like this will give 6 buttons equal widths displayed horizontally.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:layout_height="wrap_content" android:id="#+id/button1"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
<Button android:layout_height="wrap_content" android:id="#+id/button2"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:layout_height="wrap_content" android:id="#+id/button3"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
<Button android:layout_height="wrap_content" android:id="#+id/button4"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:layout_height="wrap_content" android:id="#+id/button5"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
<Button android:layout_height="wrap_content" android:id="#+id/button6"
android:text="Button" android:layout_width="0dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
As long as you keep the layout_width to be 0dp, and set the weight to be 1, Android will automatically set the widths to be equal, no matter what number of buttons you have.

Categories

Resources