Align Textviews in different rows using layout_weight parameter - android

I want to show a list of flights on a listview. And I want to have them all of them align. I have used a LinearLayout, with gravity and padding. But I want to reduce the space for the 4th column, so then I can do bigger the size of the text. I have tried to set the layout_weight of this element to 0 and all of the rest to 1. But it doesnt work. So far I have this
Any ideas?

If you are going to use ListView with a list of LinearLayout view's (I would go with a TableRow list put into a TableLayout), then I would suggest predefining the width of each column in percentage of the total space (i.e. how much of the screen would you allow the column to allocate). Something among the lines:
// basically you build your adapter here
LinearLayout.LayoutParams wrapWrapLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int[] columnWidths = new int[]{20, 20, 20, 20, 20};
ArrayList<LinearLayout> tableRows = new ArrayList<LinearLayout>();//this is the adapter
LinearLayout row = new LinearLayout(this);
//add a header
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(headerColor);
row.addView(makeTableRowWithText(headerForCol1, columnWidths[0]));
row.addView(makeTableRowWithText(headerForCol2, columnWidths[1]));
row.addView(makeTableRowWithText(headerForCol3, columnWidths[2]));
row.addView(makeTableRowWithText(headerForCol4, columnWidths[3]));
row.addView(makeTableRowWithText(headerForCol5, columnWidths[4]));
tableRows.add(row);
for(int i = 0; i < numberOfItemsInTheFlightsTable; i++) {
row = new LinearLayout(this);
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.addView(makeTableRowWithText(col1Text, columnWidths[0]));
row.addView(makeTableRowWithText(col2Text, columnWidths[1]));
row.addView(makeTableRowWithText(col3Text, columnWidths[2]));
row.addView(makeTableRowWithText(col4Text, columnWidths[3]));
row.addView(makeTableRowWithText(col5Text, columnWidths[4]));
tableRows.add(row);
}
//util method
private TextView recyclableTextView;
public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
recyclableTextView = new TextView(this);
recyclableTextView.setText(text);
recyclableTextView.setTextColor(Color.BLACK);
recyclableTextView.setTextSize(20);
recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);
return recyclableTextView;
}
I mean, the trick is that you predefine the percentage of screen allocated by each column.

Do the following
LinearLayout LL1 containing the first 4 columns
LinearLayout LL2 containing the last column
RelativeLayout RL contains LL1 and LL2
You can now position LL2 to the right of the container
EDITED

Related

Generate Layout Inside a Table Row Programmatically

I'm trying to add a Linear Layout inside a programmatically generated Table Row layout. The linear layout never seems to show. I have tried setting the width and height in the program yet nothing helped.
TableLayout ll = (TableLayout) view.findViewById(R.id.info_table);
TableRow row=new TableRow(getContext());
row.setBackgroundColor(RED);
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin=20;
int topMargin=20;
int rightMargin=20;
int bottomMargin=10;
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
row.setLayoutParams(tableRowParams);
TextView address = new TextView(getContext());
address.setMinimumWidth(320);
address.setMaxWidth(320);
address.setText("Rating");
address.setTypeface(null, Typeface.BOLD);
address.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
row.addView(address);
View dummyView = new View(getContext());
LinearLayout.LayoutParams dummyParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,300);
dummyParams.weight = 1f;
dummyView.setLayoutParams(dummyParams);
dummyView.setBackgroundColor(Color.BLACK);
row.addView(dummyView);
row.bringChildToFront(dummyView);
ll.addView(row,0);
I can see only the red color being set by the row but not the black color being set by the Layout.
you can do like below example, you can create child view in parent view :
my code working in this manner may be it helps you .
LinearLayout linear=new LinearLayout(this);
linear.setLayoutParams(new
android.view.ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tableRowParams.addView(linear);

Fill the layout with variable count of TextViews

I need to show the TextViews based on the info received from a server. E.g. I got 7 words from the server . I need to put every word in a different TextView to make it clickable. The textviews should fill the screen of the device from left to right in the lines. When the right border is reached then the next TextViews should be placed on the next line and so on.
The quantity of TextViews is variable and the words in the Textviews is different as well.
Create new textView instance and setLayoutparams to them.
Example,
TextView[] tx = new TextView[10];
TableRow[] tr = new TableRow[10];
for(i=0; i<10; i++) {
tx[i] = new TextView(this);
tx[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setText("Data")
tr[i] = new TableRow(this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i]);
// and then adding table row in tablelayout
}
For your problem you can use single textview and set spannable string to the textview.
Within that string you can provide clicks you want.
I found the solution.
I won't put the whole code here. Only main parts.
There is vertical LinearLayout.
We need to calculate the width of the layout. I couldn't do it because I do all calculations before it is drawed.
I'm getting the screen width in dips:
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpWidth = outMetrics.widthPixels / density;
int displayWidth = (int) dpWidth;
This is the free space available to put the Textviews.
Add LinearLayout to parent. Create a Textview and calculate the width:
// Calculate size of the button
Rect bounds = new Rect();
Paint textPaint = menuCategoryTV.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.width();
Then check if there is a room to place the Textview in the layout. To get it deduct TextView's width from available free space on the screen. Of course there is a space for the first textView. Until your TextView is not very long. But after filling up the layout by TextViews there will be no room for new elements. Create new LinearLayout, add it to parent and reset availble room to initial value.

Programmatically LinearLayout Weight

I'm trying to develop similar to grid but using LinearLayout. I would like to have 3 images and exact bottom text after images in single row.
What I have tried:
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
ImageView icon = new ImageView(context);
Item item = getItem(page, index);
Log.e("tag", item.getDrawable());
imageLoader.displayImage(item.getDrawable(), icon, R.drawable.ic_launcher);
icon.setPadding(15, 15, 15, 15);
layout.addView(icon);
TextView label = new TextView(context);
label.setTag("text");
label.setText(item.getName());
label.setTextColor(Color.BLACK);
label.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
label.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.setWeightSum(3f);
layout.addView(label);
I've a view method which returns Viewso I return return layout; at the end of the method.
Here I 've given weight 3 button this is not working for me. And code show more then 3 images in row with text but would like to have weight 3 images and bottom text .
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
or
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
I would define a TableLayout with as many TableRows as you need. On each of those TableRows, I'd add a LinearLayout with VERTICAL orientation consisting of the two Views you need: ImageView and TextView.
This is the LinearLayout where you should set a weight of 1 (to all of them). You will have to get the screen's width and see whether the new LinearLayout to be added still fits the current row. If not, simply start a new TableRow.
To get the width of the screen you can use this:
final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
final WindowManager.LayoutParams params = getWindow().getAttributes();
The screen's width might be accessed via the params.width attribute, just compare it with your LinearLayout's .getWidth() method and keep an incremental account (a float) of the current TableRow's width to help you determine if the current item should be placed in an existing row or a new one.
Programmtically setting Linear Layout weight
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);

Remove arbitrary gap between TableRow in TableLayout

I am using a TableLayout to print nine pictures. For some reason, I am getting a big gap between rows as shown in the image below. I set the background to green so the gaps are easy to see. My TableLayout is created programmatically. How do I fix this problem so that the gap between rows is not so big?
I have already tried tableRowParams.setMargins(0,0,0,0).
BTW: No I don't want to use ListView, etc.
I have been messing around with the code a lot trying to fix the problem. Below is simply the current state of the code:
EDIT: CORRECT IMAGE:
EDIT: the code now will work fine (thanks to #Guian):
public class FacialExpressionImagesTable extends TableLayout {
public FacialExpressionImagesTable(Context context, List<Bitmap> imageList, int sideDimension, int tableWidth, int tableHeight) {
super(context);
setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setBackgroundColor(Color.BLUE);
setContent(imageList, context, sideDimension);
}
private void setContent(List<Bitmap> imageList, Context context, final int sideDimension) {
final int iHeight = imageList.get(0).getHeight();
final int iWidth = imageList.get(0).getWidth();
int ndx = 0;
for (int r = 0; r < sideDimension; r++) {
TableRow tableRow = new TableRow(context);
TableLayout.LayoutParams forRow = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tableRow.setLayoutParams(forRow);
tableRow.setBackgroundColor(Color.RED);
TableRow.LayoutParams elementLayout = new TableRow.LayoutParams(iWidth, LayoutParams.WRAP_CONTENT, 1);
tableRow.requestLayout();
for (int c = 0; c < sideDimension; c++) {
ImageView element = new ImageView(context);
element.setLayoutParams(elementLayout);
element.setAdjustViewBounds(true);
element.setPadding(0, 0, 3, 3);
element.setBackgroundColor(Color.GREEN);
element.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
element.setImageBitmap(imageList.get(ndx++));
element.requestLayout();
tableRow.addView(element);
}
addView(tableRow);
}
}
}
first : be aware that you exchange width and height in :
new TableRow.LayoutParams(iHeight, iWidth);
But anyway, you can't give your table itesm the size of the bitmap's getHeight and getWidth since they will be resized ( depending on the screen size, screen density etc ... you would have to compute the new size according to density... )
here I think they are reduced. that's why the height of the row is too big.
set your layout params so the element take wrap_content in height and 0dip with a layout_weight to 1 in width;
TableRow.LayoutParams elementLayout = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1 );
then the table row take wrap content as height :
TableLayout.LayoutParams forRow = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if image are not scaled as needed, you'll may have to set a scale type to your ImageViews : ( using setScaleType )
elementLayout.setScaleType(ScaleType.CENTER_INSIDE); // or
FIT_CENTER... not quite sure
It should be good, tell if its not.
hope that helps.
Also try setting padding to 0 so that there is no padding inside each row of your table

android layout - WRAP_CONTENT from right to left possible?

I have a TextView and an ImageButton in a linear layout (horizontal). Total width I have is 300 pixel. Button image is 50x50. Max width I can use for text is 250. The code below works perfect if the text width is less than 250 pixels (WRAP_CONTENT work nice).
// create relative layout for the entire view
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.HORIZONTAL);
// create TextView for the title
TextView titleView = new TextView(this);
titleView.setText(title);
layout.addView(titleView);
// add the button onto the view
bubbleBtn = new ImageButton(this);
bubbleBtn.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
layout.addView(bubbleBtn);
Problem comes when the text occupies more than 250 pixels. Button gets pushed out and becomes invisible within that 300 pixel space.
What I want is this: Allocate 50 pixels width for the image. WRAP_CONTENT in the remaining 250 pixels. In other words, instead of filling in from left, fill in from the right. Is Gravity the right thing to use in this context? How and where should I use it in the code?
Or any other better way of doing this?
Use a RelativeLayout instead of a LinearLayout. Set the LayoutParams of each View as follows:
// add the button onto the view
bubbleBtn = new ImageButton(this);
bubbleBtn.setId(1); // should set this using a ids.xml resource really.
RelativeLayout.LayoutParams bbLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
bbLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
bbLP.addRule(RelativeLayout.CENTER_VERTICAL);
layout.addView(bubbleBtn, bbLP);
// create TextView for the title
TextView titleView = new TextView(this);
titleView.setText(title);
titleView.setGravity(Gravity.RIGHT);
RelativeLayout.LayoutParams tvLP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tvLP.addRule(RelativeLayout.LEFT_OF, 1);
tvLP.addRule(RelativeLayout.CENTER_VERTICAL);
layout.addView(titleView, tvLP);

Categories

Resources