RelativeLayout like TableLayout - android

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.

Related

Creating multiple views

I am trying to inflate a view multiple times.
my view consists of one imageview and a textview below it and placing it at particular position.
Below is my item.xml which I am inflating multiple times:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100dp"
android:background="#android:color/holo_blue_dark"
android:layout_height="100dp">
<ImageView
android:layout_gravity="center"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#mipmap/ic_launcher"
android:id="#+id/imageView"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="20dp"
android:textSize="12sp"
android:textStyle="bold"
android:text="Large Text"
android:id="#+id/textView" />
</LinearLayout>
Here is my code with inflate:
for (int i = 0; i < 1; i++) {
final View v = linf.inflate(R.layout.item, null);
TextView tvs = (TextView) v.findViewById(R.id.textView);
ImageView ivs = (ImageView) v.findViewById(R.id.imageView);
tvs.setText(i+"");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
int w = (mWidth/2)-50;
int h =(mHeight/2)-50;
params.leftMargin = w;
params.topMargin = h;
Log.e("W-H", mWidth + "-" + mHeight);
rr.addView(v,params);
}
I am able to place the item.xml successfully but its not fitting screen properly I have set height and width fixed 100dp.
Here is what I am getting
here
The constructor for LayoutParams is in pixels, so you have to convert to dps for it to display correctly on your screen. This can be accomplished as in this stackoverflow answer:
int width_dps = 100;
int height_dps = 100;
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
int width_pixels = (int) (width_dps * scale + 0.5f);
int height_pixels = (int) (height_dps * scale + 0.5f);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width_pixels, height_pixels);
Alternatively, if you are using a fixed size, you can update your xml to allow wrap_content to work correctly. You will be overriding the LinearLayout params, so you can update your subviews:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
and update a subview (android:layout_width="100dp"):
<TextView
android:gravity="center"
android:layout_width="100dp"
android:layout_height="20dp"
android:textSize="12sp"
android:textStyle="bold"
android:text="Large Text"
android:id="#+id/textView" />

Why are programmatically set weights for Android linear layout columns not working correctly?

I am attempting to create a key for an above pie chart within this Linear layout. However, the weights aren't working properly, and the three columns are split up equally. Does anyone know what may be causing this? Thanks!
Layout XML:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tableLayout1"
android:orientation="vertical"
android:layout_centerHorizontal="true">
<TableRow android:gravity="center"
android:id="#+id/tableRow"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:weightSum="4">
<ImageButton
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/aiButton"
android:layout_gravity="center_horizontal"
android:src="#drawable/barchartwhite"
android:background="#CCAF00"
android:layout_weight="1"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
android:text="TP Activity"
android:id="#+id/textView2"
android:layout_gravity="center|center_vertical"
android:textSize="40sp"
android:background="#CCAF00"
android:layout_weight="3"
android:layout_alignParentTop="true"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:gravity="center_vertical" />
</TableRow>
<TableRow android:gravity="center"
android:id="#+id/tableRowSub"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Percentage of Activity per TP"
android:id="#+id/textViewSub"
android:layout_gravity="center"
android:textSize="16sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<com.shannonsystemsllc.ediconnect.PieChartView
xmlns:chart="http://schemas.android.com/apk/res-auto"
android:id="#+id/piechart"
android:paddingRight="12dp"
android:paddingLeft="12dp"
android:layout_width="300sp"
android:layout_height="300dp"/>
</TableRow>
</LinearLayout>
Code for creating key:
for (int i = 0; i < customers.size(); i++) {
int c[] = {Color.parseColor("#FF4B66"),Color.parseColor("#00A9AC"),Color.parseColor("#70A200"),Color.parseColor("#FAB448"),Color.parseColor("#BFBFBF"),Color.GREEN,custColor,Color.CYAN,Color.BLUE};
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT);
TableLayout.LayoutParams tl = new TableLayout.LayoutParams();
final float scale = getActivity().getResources().getDisplayMetrics().density;
int pixels = (int) (30 * scale + 0.5f); //set pixels to dp
TableRow row = new TableRow(activity);
row.setWeightSum(9);
//first row
tl.weight = 1;
lp.weight = 6;
lp.height = pixels;
row.setLayoutParams(lp);
TextView tv1a = new TextView(getActivity());
tv1a.setTextSize(22);
tv1a.setText(customers.get(i));
tv1a.setLayoutParams(lp);
tv1a.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
TextView tv1b = new TextView(getActivity());
tv1b.setTextSize(24);
Float perFloat = ((float)pieChartValues[i]/dataTotal*100);
remainderTotal = remainderTotal - perFloat.intValue();
String percentage;
if (perFloat.intValue() == 0)
{
percentage = ("1%");
}
else
{
percentage = (perFloat.intValue() + "%");
}
lp.weight = 2;
tv1b.setText(percentage);
tv1b.setLayoutParams(lp);
tv1b.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
lp.weight = 1;
ImageView tv1c = new ImageView(getActivity());
tv1c.setLayoutParams(lp);
tv1c.setBackgroundColor(c[i]);
row.setWeightSum(3);
row.addView(tv1b);
row.addView(tv1c);
row.addView(tv1a);
row.setId(i);
ll.addView(row);
}
Screenshot:
Set the weight of the contents inside each row as follows:
- For the percentage TextView, set the weight to 3.
- For the ImageView, set the weight to 8.
- For the name Textview, set the weight to 7.
This will result to the entire row to look slightly offset from the centre. Make sure all three views are set to match parent width.
Once you set weights for the views call:
yourLinearLayout.invalidate()
Try this out and see if it works.

Dynamically created ImageView not respecting RelativeLayout rules

I'm adding ImageViews dynamically to a RelativeLayout. I'm trying to align each image to the right of the last image. The initial image aligns correctly but when I set the next image to align to the right side of the last image, it displays at the top left of the screen, disregarding the alignment rules.
Hierarchy View in the Android Device Monitor is indicating that the IDs are correctly getting set and the ImageView is recognizing that it's supposed to align to the id of the last ImageView.
List<String> image_urls = rally.getTransportationImgs();
List<String> methods = rally.getTransportationStrs();
ArrayList<ImageView> IMGS = new ArrayList<ImageView>();
for(int i = 0; i < methods.size(); i++) {
String method = methods.get(i);
for(int j = 0; j < image_urls.size(); j++) {
String img_url = image_urls.get(j);
if(img_url.toLowerCase().contains(method.toLowerCase()) == true) {
ImageView methodImage = new ImageView(this);
methodImage.setId(j + 100);
IMGS.add(methodImage);
RelativeLayout detailsLayout = (RelativeLayout) findViewById(R.id.details_layout);
TextView transportationText = (TextView) detailsLayout.findViewById(R.id.transportationText);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (IMGS.size() > 1) {
params.addRule(RelativeLayout.RIGHT_OF, IMGS.get(IMGS.size() - 1).getId());
params.addRule(RelativeLayout.ALIGN_TOP, IMGS.get(IMGS.size() - 1).getId());
params.addRule(RelativeLayout.END_OF, IMGS.get(IMGS.size() - 1).getId());
params.height = 5000;
params.width = 65;
} else {
params.addRule(RelativeLayout.RIGHT_OF, transportationText.getId());
params.addRule(RelativeLayout.ALIGN_TOP, transportationText.getId());
params.addRule(RelativeLayout.END_OF, transportationText.getId());
params.height = 65;
params.width = 65;
}
methodImage.setLayoutParams(params);
detailsLayout.addView(methodImage);
Picasso.with(getApplicationContext()).load(img_url).fit().centerCrop().placeholder(R.drawable.ic_launcher).into(methodImage);
}
}
}
XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:orientation="vertical"
android:weightSum="1"
android:id="#+id/details_layout">
<ImageView
android:layout_width="match_parent"
android:layout_height="275dp"
android:id="#+id/image" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/name2"
android:layout_below="#id/image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/date2"
android:layout_below="#id/name2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/creator_name2"
android:layout_below="#id/date2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/venues"
android:layout_below="#id/creator_name2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/transportationText"
android:layout_below="#id/venues"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/categories"
android:layout_below="#id/transportationText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
For debugging purposes, I set the image height obnoxiously large. The gray is part of an image that is supposed to go to the right side of the ImageView that correctly aligns next to "Transportation:"
The problem is with this line:
methodImage.setId(j + 100);
If there's more than one Object in methods array there will be conflict in ImageViews ids. You're generating your ids based on only the index of the inner array (j).
For example if:
There are two items in methods
There are three items in image_urls
Your ImageViews would have ids: [101, 102, 103, 101, 102, 103]
Therefore you will add multiple Views with the same ids.
To solve the issue either generate ids based on both i and j, or generate them in more conventional way.
EDIT:
Well, the other issue is that you're trying to set RelativeLayout Rules that are aligning a particular View to the same View.
Take a look at your code:
You're creating an ImageView, setting its id and immediately adding it to the IMGS list, with this:
IMGS.add(methodImage);
And then you're trying to set your RelativeLayout Rules, that should align your ImageView, but you're referencing to the last item of the IMGS list, with:
IMGS.get(IMGS.size() - 1)
And the last item in the array is the same View, you're trying to set up!
To solve the issue either:
a) Move IMGS.add(methodImage); after the if-else, and change the if condition to if (IMGS.size() > 0) {
or
b) Change the if body to:
params.addRule(RelativeLayout.RIGHT_OF, IMGS.get(IMGS.size() - 2).getId());
params.addRule(RelativeLayout.ALIGN_TOP, IMGS.get(IMGS.size() - 2).getId());
params.addRule(RelativeLayout.END_OF, IMGS.get(IMGS.size() - 2).getId());

get Items from listview with adapter

I need to do something a little unusual. I'm carrying a listview with custom adapter and everything works fine. Each item of listview has 4 TextView and a button. The button when it is clicked makes certain actions in my database, just tell them to simplify the issue that marks a value of 0-1, more specifically valid if I click I earned an inscription. By clicking the background of the button changes to a icon with a ticket. Now I need to make a function that validates all entries at once, that it is ready. But now I need to update the button and give the corresponding background. But I find no way to change each item that particular item.
If you wonder what I explain, please consult me.
Layout
<?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"
android:orientation="vertical" >
<TextView
android:id="#+id/txtNombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/txtTicket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtNombre"
android:paddingLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/txtOrden"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTicket"
android:paddingLeft="10dp"
android:text="" />
<TextView
android:id="#+id/txtAsiento"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtOrden"
android:paddingLeft="10dp"
android:visibility="gone"
android:text="" />
<TextView
android:id="#+id/txtNumero"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtAsiento"
android:paddingLeft="10dp"
android:visibility="gone"
android:text="" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtOrden"
android:layout_alignParentRight="true"
android:layout_marginRight="23dp"
android:background="#drawable/btn_green_small"
android:maxHeight="48dp"
android:maxWidth="80dp"
android:shadowColor="#A8A8A8"
android:text="Validar"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/txtMensaje"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="SDSDSDS"
android:layout_marginRight="18dp"
android:visibility="gone"
android:textSize="10dp" />
</RelativeLayout>
Change background button
if(rowItem.getValidado()==1){
holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
holder.btn.setText("");
holder.txtMensaje.setText("E-ticket ya validado");
holder.txtMensaje.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.rightMargin = 63;
params.topMargin = 10;
params.bottomMargin = 5;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.btn.setLayoutParams(params);
}else{
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
RowItem item_click = getItem(position);
Connection cn = new Connection();
Button b = (Button)v.findViewById(R.id.button1);
b.setBackgroundResource(R.drawable.icon_big_check);
b.setText("");
}
That need to do, but from the activity and not from the adapter.
I found the solution, I could iterate through the items in the listview and got what I wanted.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listView = (ListView) findViewById(R.id.listView1);
View v;
Button b;
for (int i = 0; i < listView.getCount(); i++) {
v = listView.getChildAt(i);
b = (Button) v.findViewById(R.id.button1);
b.setBackgroundResource(R.drawable.icon_big_check);
b.setText("");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.rightMargin = 63;
params.topMargin = 10;
params.bottomMargin = 5;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
b.setLayoutParams(params);
System.out.println(b);
}
}

Textview with long text pushes out other views in GridLayout despite ellipsize=end

My problem is very similar to How to get a layout where one text can grow and ellipsize, but not gobble up the other elements on the layout, but read on below why I can't use TableLayouts as proposed there.
I'm trying to create a listview row that basically looks like this:
| TextView | View 1 | View 2 |
All views contain variable width elements. The TextView has ellipsize="end" set. View 1 should align left of the TextView, while View 2 should align to the right of the screen. So, normally, there would be whitespace between View 1 and View 2. As the text in the TextView grows longer, the TextView should grow, pushing View 1 to the right until there is no more whitespace left. Then, ellipsize should kick in, cutting of the text in TextView and appending an ellipsis ("...") at the end.
So, the result should look something like this:
+----------------------------------------+
| short text [view1] [view2] |
+----------------------------------------+
| long text with ell ... [view1] [view2] |
+----------------------------------------+
I've tried:
TableLayouts, but they seem to make scrolling extremely slow on some devices.
RelativeLayouts, but I either had overlapping views, or view1 or view2 disappeared completely.
GridLayouts, but the TextView always grows until it takes up the whole width of the screen, thus pushing view1 and view2 out of the screen.
This is the GridLayout I tried:
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_gravity="left|fill_horizontal"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
<TextView
android:layout_gravity="left"
android:text="(view1)" />
<TextView
android:layout_gravity="right"
android:text="(view2)" />
</GridLayout>
View 1 and View 2 are not really TextViews, I just used them in the example to simplify things.
Is there any way to achieve this without using TableLayouts?
EDIT:
As requested, here is my attempt at solving this with a RelativeLayout. The TextView takes up the full width of the screen in this case, so neither view1 nor view2 are visible.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/rl0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
<TextView
android:id="#+id/rl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/rl0"
android:layout_marginLeft="10dp"
android:text="(view1)" />
<TextView
android:id="#+id/rl2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/rl1"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="(view2)" />
</RelativeLayout>
I seem to have found a potential solution to prevent a TextView in GridLayout from growing unboundedly and pushing out other views. Not sure if this has been documented before.
You need to use fill layout_gravity and set an arbitrary layout_width or width on the long TextView in need of ellipsizing.
android:layout_gravity="fill"
android:layout_width="1dp"
Works for both GridLayout and android.support.v7.widget.GridLayout
I'm a big fan of LinearLayouts, so here's my suggestion using those:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(view1)" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="(view2)" />
</LinearLayout>
I will suggest you to play with layout_weight property of your widget
Example:
<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:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10">
<LinearLayout
android:id="#+id/ll_twoViewContainer"
android:layout_weight="8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/rl0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_weight="1"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text" />
<TextView
android:id="#+id/rl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/rl0"
android:layout_weight="1"
android:minWidth="120dp"
android:text="(view1)" />
</LinearLayout>
<TextView
android:id="#+id/rl2"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/rl1"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="(view2)" />
</LinearLayout>
</LinearLayout>
finally your layout will look like as follow:
+----------------------------------------+
| short text [view1] [view2] |
+----------------------------------------+
| long text with ell ... [view1] [view2] |
+----------------------------------------+
I think you should create custom layout for your purpose. I don't know how to do this using only default layouts/view and make it work for all cases.
The trick which worked for me was to use maxWidth to restrict the width of the first view. You need to do it with Java, here is the basic logic:
firstView.setMaxWidth(parentView.getWidth() - view2.getWidth() - view1.getWidth() - padding * 2);
Not pretty, but it works.
I think there's just a small issue on the layout that could be solved, anchoring the view3 to the right and start from there to force the view to have a delimited area (hence being able to properly set the ellipse):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rl3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="(view2)" />
<TextView
android:id="#+id/rl2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/rl3"
android:text="(view1)" />
<TextView
android:id="#+id/rl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/rl2"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
</RelativeLayout>
Hope this helps...
Regards!
Try this
<?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="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="(view1)"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="(view2)"/>
</LinearLayout>
</LinearLayout>
Currently, all views are centered. You can change android:gravity property to meet your needs. For example, you may want to align view1 right and view2 left in which case last two LinearLayouts would look something like (with 5dp margin on the right and left respectively):
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center|right">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginRight="5dp"
android:text="(view1)"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center|left">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginLeft="5dp"
android:text="(view2)"/>
</LinearLayout>
I find my solution for the case number 2 (the one with a long text):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="3" >
<TextView
android:id="#+id/rl0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:ellipsize="end"
android:singleLine="true"
android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
<TextView
android:id="#+id/rl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:text="(view1)" />
<TextView
android:id="#+id/rl2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:text="(view2)" />
</LinearLayout>
The real problem is case one, and i didn't try a lot of things for this. I hope it helps (and if i have more spare time, i will try to achieve first one!).
If the views on the right get pushed over by the text by design, you might as well use a ListView instead of a GridView.
You would just need to make the base of the list item layout a RelativeLayout, and set rules like this:
You can set the two views on the right to alignParentRight (using android:layout_alignParentLeft="true"), but make sure the first view stays to the left of the second so it will push itself to the left as the views stretch out.
You can make the TextView on the left align to the left, but stay to the left of the first view (using android:layout_toLeftOf="#+id/viewId") so it won't overlap with the views.
Try using Layout Weight
<TableRow
android:id="#+id/tableRow3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tableRow2"
android:layout_alignParentBottom="true"
android:gravity="center"
android:weightSum="10"
android:background="#android:color/black" >
<TextView
android:id="#+id/txtInningsTotal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center"
android:text="0"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/txtTeamOneTotal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2.5"
android:gravity="center"
android:text="0"
android:textColor="#android:color/white" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2" />
<TextView
android:id="#+id/txtTeamTwoTotal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2.5"
android:gravity="center"
android:text="0"
android:textColor="#android:color/white" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2" />
<TextView
android:id="#+id/txtGrandTotal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="center"
android:text="0"
android:textColor="#android:color/white" />
</TableRow>
Here i have taken table row in which there is layout weight sum which is of 10 means that it is 100% width of its parent. and in all its child views i have set width to 0Dp and given weight to 1 or 2. so that it will take up to that percent of total 10. so the layout will be adjusted accordingly screen and also there will be no issue of overlapping.
If i have understood you correctly then this is the answer you wanted.
Hope it Helps!
First, you must layout [view 2] to parent Right;
Again, you reference the reference to the last two layout!
<Relativelayout android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeft="#id/view2"
android:gravity="left">
<TextView
android:id="#+id/shortORlongtTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/view1"
android:ellipsize="end"
android:maxLines="1"
android:textSize="18dp"/>
<TextView
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
I had the same problem with the grid layout. what i did is given a fixed width for the text view and also given layout_columnWeight property for each text view then the issue was fixed ,hope it helps ...
<TextView
android:id="#+id/txtName"
style="#style/MyDetailTitle"
android:layout_width="#dimen/detail_length"
android:layout_height="wrap_content"
android:text="#string/app_name"
app:layout_column="3"
app:layout_columnWeight="1"
app:layout_gravity="start"
app:layout_row="1" />
GridLayout is like the other things on Android : flawed by design.
You will need a custom Layout, the following example will allow you to layout things like:
[ label | short text | very long label | short text ]
[ long label | very very very | label | very long text ]
[ | long text | | ]
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class TwoColumsGridLayout extends ViewGroup {
private final List<List<View>> rows;
private int rowCount = 0;
private int firstColumWidth;
private int secondColumWidth;
private int thirdColumWidth;
private int fourthColumnWidth;
private final List<Integer> rowHeights = new ArrayList<>();
private final List<List<Integer>> cellHeights = new ArrayList<>();
private final List<Integer> firstCellsWidths = new ArrayList<>(4);
private final List<Integer> thirdCellsWidths = new ArrayList<>(4);
public TwoColumsGridLayout(Context context, int rowCount) {
super(context);
rows = new ArrayList<>(rowCount);
}
public void add(Context ctx, TextView l1, View t1, TextView l2, View t2) {
final List<View> row = new ArrayList<>(4);
row.add(l1);
row.add(t1);
row.add(l2);
row.add(t2);
rows.add(row);
this.addView(l1);
this.addView(t1);
if (l2 != null)
this.addView(l2);
if (t2 != null)
this.addView(t2);
this.rowCount++;
}
public int getRowCount() {
return rowCount;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int curLeft = 0;
int curBottom;
int curRight;
int curTop = 0;
int i = 0;
for (List<View> row : rows) {
final int rowHeight = this.rowHeights.get(i);
final List<Integer> rowCellHeights = this.cellHeights.get(i);
final View v0 = row.get(0);
curLeft = 0;
curRight = curLeft + this.firstColumWidth;
if (v0 != null) {
curBottom = curTop + rowCellHeights.get(0);
// Right align
v0.layout(curLeft + this.firstColumWidth - this.firstCellsWidths.get(i), curTop + 7, curRight, curBottom + 7);
}
//
final View v1 = row.get(1);
curLeft += this.firstColumWidth;
curRight = curLeft + this.secondColumWidth;
if (v1 != null) {
curBottom = curTop + rowCellHeights.get(1);
v1.layout(curLeft, curTop, curRight, curBottom);
}
//
final View v2 = row.get(2);
curLeft += this.secondColumWidth;
curRight = curLeft + this.thirdColumWidth;
if (v2 != null) {
curBottom = curTop + rowCellHeights.get(2);
// Right align
v2.layout(curLeft + this.thirdColumWidth - this.thirdCellsWidths.get(i), curTop + 7, curRight, curBottom + 7);
}
//
final View v3 = row.get(3);
curLeft += this.thirdColumWidth;
curRight = curLeft + this.fourthColumnWidth;
if (v3 != null) {
curBottom = curTop + rowCellHeights.get(3);
v3.layout(curLeft, curTop, curRight, curBottom);
}
curTop += rowHeight;
i++;
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
// Compute first column width
firstColumWidth = 0;
for (List<View> row : rows) {
final View v = row.get(0);
if (v != null) {
v.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
measureChild(v, widthMeasureSpec, heightMeasureSpec);
final int w = v.getMeasuredWidth();
if (firstColumWidth < w) {
firstColumWidth = w;
}
}
}
// Compute third column width
thirdColumWidth = 0;
for (List<View> row : rows) {
final View v = row.get(2);
if (v != null) {
v.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
measureChild(v, widthMeasureSpec, heightMeasureSpec);
final int w = v.getMeasuredWidth();
if (thirdColumWidth < w) {
thirdColumWidth = w;
}
}
}
secondColumWidth = (parentWidth - firstColumWidth - thirdColumWidth) / 2;
fourthColumnWidth = parentWidth - firstColumWidth - secondColumWidth - thirdColumWidth;
// Clear
this.rowHeights.clear();
this.cellHeights.clear();
this.firstCellsWidths.clear();
this.thirdCellsWidths.clear();
// Compute heights
int height = 0;
for (List<View> row : rows) {
final ArrayList<Integer> rowCellHeights = new ArrayList<>(4);
cellHeights.add(rowCellHeights);
int rowHeight = 0;
// First column
final View v0 = row.get(0);
if (v0 != null) {
int h = v0.getMeasuredHeight();
this.firstCellsWidths.add(v0.getMeasuredWidth());
rowCellHeights.add(h);
if (rowHeight < h) {
rowHeight = h;
}
} else {
this.firstCellsWidths.add(0);
}
// Second column
final View v1 = row.get(1);
if (v1 != null) {
v1.setLayoutParams(new ViewGroup.LayoutParams(secondColumWidth, LayoutParams.WRAP_CONTENT));
measureChild(v1, widthMeasureSpec, heightMeasureSpec);
int h = v1.getMeasuredHeight();
rowCellHeights.add(h);
if (rowHeight < h) {
rowHeight = h;
}
}
// Third column
final View v2 = row.get(2);
if (v2 != null) {
int h = v2.getMeasuredHeight();
this.thirdCellsWidths.add(v2.getMeasuredWidth());
rowCellHeights.add(h);
if (rowHeight < h) {
rowHeight = h;
}
} else {
this.thirdCellsWidths.add(0);
}
// Fourth column
final View v3 = row.get(3);
if (v3 != null) {
v3.setLayoutParams(new ViewGroup.LayoutParams(fourthColumnWidth, LayoutParams.WRAP_CONTENT));
measureChild(v3, widthMeasureSpec, heightMeasureSpec);
int h = v3.getMeasuredHeight();
rowCellHeights.add(h);
if (rowHeight < h) {
rowHeight = h;
}
}
height += rowHeight;
this.rowHeights.add(rowHeight);
}
setMeasuredDimension(parentWidth, height);
}
}
Have fun.
TableLayout will give expected behavior. May cause performance issue as question's author mention, but works great with simple layout. If the row is repeatable and scrollable, consider use gridview instead
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
android:shrinkColumns="0"
>
<TableRow>
<TextView/>
<View1/>
<View2/>
</TableRow>
</TableLayout>

Categories

Resources