How to get layout working programmatically - android

As my Android apps are growing I need to include dynamic characteristics that include growing/reducing tables.
Therefore, I have switched from XML defined to programmatic methods.
My main XML, containing the basic table layout is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table_layout_abonos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="top" >
</TableLayout>
</LinearLayout>
And then I try to define the header of the table using a TableRow that contains a set of titles for each table row by means of different TextView.
I have implemented this as follows:
public void añadeCabeceraTablaAbonos() {
TableLayout layoutTablaAbonados = (TableLayout) findViewById(R.id.table_layout_abonos);
int rowHeight = getStandardPixels(40);
TableRowTitulos cabeceraTablaAbonados = new TableRowTitulos(this);
cabeceraTablaAbonados.setId(100);
/*
* android:id="#+id/cultivo_auxiliares" android:layout_width="400dp"
* android:layout_height="40dp" android:layout_marginLeft="40dp"
* android:gravity="center"
* android:text="#string/cultivo_parcela_auxiliar"
* android:textAppearance="?android:attr/textAppearanceMedium"
*
* <TableRow android:layout_marginBottom="10dp"
* android:background="#color/rojo_dupont" >
*/
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 0, 0, getStandardPixels(10));
cabeceraTablaAbonados.setLayoutParams(tableRowParams);
header_abonado_cultivo = new TextView(this);
header_abonado_abono = new TextView(this);
header_abonado_fecha = new TextView(this);
header_abonado_dosis = new TextView(this);
header_abonado_dosificacion = new TextView(this);
header_abonado_metodo = new TextView(this);
header_abonado_deposito_A = new TextView(this);
header_abonado_deposito_B = new TextView(this);
header_abonado_deposito_C = new TextView(this);
header_abonado_deposito_D = new TextView(this);
header_botonera = new TextView(this);
header_abonado_cultivo.setId(101);
header_abonado_cultivo.setText("CULTIVO");
header_abonado_cultivo.setGravity(Gravity.CENTER);
header_abonado_cultivo
.setWidth(getStandardPixels(ANCHO_COLUMNA_CULTIVO_ABONO));
//header_abonado_cultivo.setHeight(rowHeight);
header_abonado_cultivo.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_abono.setId(102);
header_abonado_abono.setText("ABONO");
header_abonado_abono.setGravity(Gravity.CENTER);
header_abonado_abono
.setWidth(getStandardPixels(ANCHO_COLUMNA_ABONO_ABONO));
//header_abonado_abono.setHeight(rowHeight);
header_abonado_abono.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_fecha.setId(103);
header_abonado_fecha.setText("FECHA");
header_abonado_fecha.setGravity(Gravity.CENTER);
header_abonado_fecha
.setWidth(getStandardPixels(ANCHO_COLUMNA_FECHA_ABONO));
//header_abonado_fecha.setHeight(rowHeight);
header_abonado_fecha.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_metodo.setId(104);
header_abonado_metodo.setText("MÉTODO");
header_abonado_metodo.setGravity(Gravity.CENTER);
header_abonado_metodo
.setWidth(getStandardPixels(ANCHO_COLUMNA_METODO_ABONO));
//header_abonado_metodo.setHeight(rowHeight);
header_abonado_metodo.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_dosis.setId(105);
header_abonado_dosis.setText("DÓSIS");
header_abonado_dosis.setGravity(Gravity.CENTER);
header_abonado_dosis
.setWidth(getStandardPixels(ANCHO_COLUMNA_DOSIS_ABONO));
//header_abonado_dosis.setHeight(rowHeight);
header_abonado_dosis.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_dosificacion.setId(106);
header_abonado_dosificacion.setText("DOSIFICACIÓN");
header_abonado_dosificacion.setGravity(Gravity.CENTER);
header_abonado_dosificacion
.setWidth(getStandardPixels(ANCHO_COLUMNA_DOSIFICACION_ABONO));
//header_abonado_dosificacion.setHeight(rowHeight);
header_abonado_dosificacion.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_deposito_A.setId(107);
header_abonado_deposito_A.setText("DEP. A");
header_abonado_deposito_A.setGravity(Gravity.CENTER);
header_abonado_deposito_A
.setWidth(getStandardPixels(ANCHO_COLUMNA_DEPOSITO_ABONO));
//header_abonado_deposito_A.setHeight(rowHeight);
header_abonado_deposito_A.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_deposito_B.setId(108);
header_abonado_deposito_B.setText("DEP. B");
header_abonado_deposito_B.setGravity(Gravity.CENTER);
header_abonado_deposito_B
.setWidth(getStandardPixels(ANCHO_COLUMNA_DEPOSITO_ABONO));
//header_abonado_deposito_B.setHeight(rowHeight);
header_abonado_deposito_B.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_deposito_C.setId(109);
header_abonado_deposito_C.setText("DEP. C");
header_abonado_deposito_C.setGravity(Gravity.CENTER);
header_abonado_deposito_C
.setWidth(getStandardPixels(ANCHO_COLUMNA_DEPOSITO_ABONO));
//header_abonado_deposito_C.setHeight(rowHeight);
header_abonado_deposito_C.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_abonado_deposito_D.setId(110);
header_abonado_deposito_D.setText("DEP. D");
header_abonado_deposito_D.setGravity(Gravity.CENTER);
header_abonado_deposito_D
.setWidth(getStandardPixels(ANCHO_COLUMNA_DEPOSITO_ABONO));
//header_abonado_deposito_D.setHeight(rowHeight);
header_abonado_deposito_D.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
header_botonera.setId(111);
header_botonera.setText("");
header_botonera.setGravity(Gravity.CENTER);
//header_botonera
// .setWidth(getStandardPixels(ANCHO_COLUMNA_BOTONERA_ABONO));
//header_botonera.setHeight(rowHeight);
header_botonera.setTextAppearance(this,
android.R.style.TextAppearance_Medium);
cabeceraTablaAbonados.addView(header_abonado_cultivo);
cabeceraTablaAbonados.addView(header_abonado_abono);
cabeceraTablaAbonados.addView(header_abonado_fecha);
cabeceraTablaAbonados.addView(header_abonado_metodo);
cabeceraTablaAbonados.addView(header_abonado_dosis);
cabeceraTablaAbonados.addView(header_abonado_dosificacion);
cabeceraTablaAbonados.addView(header_abonado_deposito_A);
cabeceraTablaAbonados.addView(header_abonado_deposito_B);
cabeceraTablaAbonados.addView(header_abonado_deposito_C);
cabeceraTablaAbonados.addView(header_abonado_deposito_D);
cabeceraTablaAbonados.addView(header_botonera);
//abonadoLayout
layoutTablaAbonados.addView(cabeceraTablaAbonados);
// TableRow.LayoutParams buttonParams = (TableRow.LayoutParams)header_abonado_cultivo.getLayoutParams();
// buttonParams.setMargins(15, 10, 10, 10);
}
Nevertheless, I am not able to make:
a) The header having a specific HEIGHT. I have tried replacing:
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
with
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
100); // For 100 pixels height
But the row remains the "standard" height that just wraps content.
Also, I have a similar issue with data rows (non-header) that are composed of a series of Buttons.
These buttons text will change dinamically and will stretch vertically to adapt to such string.
Nevertheless, the neighbour buttons won't stretch accordingly and so the aspect is very ugly with some buttons being taller than other ones (I won't paste more code on this as it is very similar to the other problem).
Here is an equivalent XML that does it correctly (grows all buttons accordingly to the taller one on the row):
(FIRST TABLE ROW IS HEADER AND NEXT ARE DATA)
<ScrollView
android:id="#+id/tab6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="top" >
<TableRow
android:layout_marginBottom="10dp"
android:background="#color/rojo_dupont" >
<TextView
android:id="#+id/cultivo_auxiliares"
android:layout_width="400dp"
android:layout_height="40dp"
android:layout_marginLeft="40dp"
android:gravity="center"
android:text="#string/cultivo_parcela_auxiliar"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/nombre_plaga_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:gravity="center"
android:text="#string/nombre_plaga_label"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/nombre_insecto_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:gravity="center"
android:text="#string/nombre_insecto_label"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/fecha_suelta_label"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_marginLeft="40dp"
android:gravity="center"
android:text="#string/fecha_suelta_label"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/cantidad_insecto_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:gravity="center"
android:text="#string/cantidad_insecto_label"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:layout_height="wrap_content"
android:layout_marginBottom="5dp" >
<Button
android:id="#+id/cultivo_parcela_0"
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#8ad5f0" />
<Button
android:id="#+id/nombre_plaga_0"
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#8ad5f0" />
<Button
android:id="#+id/nombre_insecto_0"
android:layout_width="180dp"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:focusableInTouchMode="false"
android:gravity="center"
android:hint="" />
<Button
android:id="#+id/fecha_suelta_0"
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#8ad5f0" />
<EditText
android:id="#+id/cantidad_insecto_0"
android:layout_width="120dp"
android:layout_height="match_parent"
android:layout_marginLeft="40dp"
android:focusableInTouchMode="false"
android:gravity="center"
android:hint=""
android:inputType="number" />
<ImageButton
android:id="#+id/insecto_0_delete"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:contentDescription="#string/delete_content_description"
android:src="#drawable/discard_dark" />
<ImageButton
android:id="#+id/insecto_0_comentario"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:contentDescription="#string/delete_content_description"
android:src="#drawable/ic_dialog_alert_holo_dark" />
</TableRow>
MORE ROWS FOLLOW WITH THE SAME SCHEMA
...
I suppose I'm doing something wrong with layouts but I cannot figure it out even after reading a lot about it.
Could someone guide me with this or provide some working code?
Thanks in advance,
Jose.

Well, it seems I found the solution !!. The main problem was that I was selecting the wrong Layout for the Views inside the row.
Conceptually, the row must have a height that is WRAP_CONTENT so it will grow dynamically with the highest View it contains. Also, each View in the row must have its hight put to MATCH_PARENT, so they will grow as the row does. This is not very intuitive for me but it is it.
So here is a portion of the code that solved the problem for me, hope this can help someone:
TableRowAbonados nuevaFila = new TableRowAbonados(this);
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin = 0;
int topMargin = 0;
int rightMargin = 0;
int bottomMargin = getStandardPixels(5);
tableRowParams.setMargins(leftMargin, topMargin, rightMargin,
bottomMargin);
nuevaFila.setLayoutParams(tableRowParams);
Button botonAbono = new Button(this);
Button botonFecha = new Button(this);
Button botonMetodo = new Button(this);
EditText celdaDosis = new EditText(this);
celdaDosis.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
nuevaFila.addView(botonAbono);
nuevaFila.addView(botonFecha);
nuevaFila.addView(botonMetodo);
nuevaFila.addView(celdaDosis);
botonAbono.getLayoutParams().height=TableRow.LayoutParams.MATCH_PARENT;
botonFecha.getLayoutParams().height=TableRow.LayoutParams.MATCH_PARENT;
botonMetodo.getLayoutParams().height=TableRow.LayoutParams.MATCH_PARENT;
celdaDosis.getLayoutParams().height=TableRow.LayoutParams.MATCH_PARENT;
layoutTablaAbonados.addView(nuevaFila);

Related

Setting stacked up layout programmatically in android

I would like to have a relative layout with linear layouts nested in between them but i am unable to understand how ill nest them programmatically
This is what i have as my xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/button_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:text="Add items" />
<LinearLayout
android:id="#+id/above_part"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button_top"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:orientation="vertical"
android:padding="2dp">
<TextView
android:id="#+id/label_farmerprovince"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Province"
android:textSize="12sp"
android:textStyle="normal" />
<EditText
android:id="#+id/fivms_farmerprovince"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/editbox_background">
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:orientation="vertical"
android:padding="2dp">
<TextView
android:id="#+id/distric_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="District"
android:textSize="12sp"
android:textStyle="normal" />
<EditText
android:id="#+id/district"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/editbox_background" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:orientation="vertical"
android:padding="2dp">
<TextView
android:id="#+id/label_farmeragriblocks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Agriblocks"
android:textSize="12sp"
android:textStyle="normal" />
<EditText
android:id="#+id/agri"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/editbox_background" />
</LinearLayout>
</LinearLayout>
This produces the layout that i want:
Now i would like to add the above layout and change it to a java way
I hav tried
//top layout
RelativeLayout newlayout = new RelativeLayout(getContext());
LinearLayout belowlayout = new LinearLayout(getContext());
LinearLayout above_part = new LinearLayout(getContext()); //lin with id of above_part
LinearLayout in_above_part_one = new LinearLayout(getContext()); //lin with id of above_part
//layouts properties
belowlayout.setOrientation(LinearLayout.HORIZONTAL);
//setids for the layouts
newlayout.setId(12);
belowlayout.setId(13);
//Button
Button additemsbtn = new Button(getContext());
additemsbtn.setText("Log In");
additemsbtn.setBackgroundColor(Color.BLACK);
//Username input
EditText username = new EditText(getContext());
additemsbtn.setId(int 1);
username.setId(2);
RelativeLayout.LayoutParams buttonDetails = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT,
);
RelativeLayout.LayoutParams usernameDetails = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
//Give rules to position widgets
usernameDetails.addRule(RelativeLayout.ABOVE, additemsbtn.getId());
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
usernameDetails.setMargins(0,0,0,50);
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);
Whatever i have started fails since am unable to know how to nest the different linear layouts,
I would probably like guidelines on how to do this nesting programmatically so that i can achieve the same thing generated by the xml file
Little example how it can be done. So, all you need to do is to add inner items to my nested layouts and configure margins/paddings etc. Also added background for better visualization.
RelativeLayout root = (RelativeLayout) findViewById(R.id.root);
Button addButton = new Button(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
addButton.setLayoutParams(params);
addButton.setId(123);
root.addView(addButton);
LinearLayout rootLinearlayout = new LinearLayout(this);
RelativeLayout.LayoutParams linearRootParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
linearRootParams.addRule(RelativeLayout.BELOW, 123);
rootLinearlayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
rootLinearlayout.setLayoutParams(linearRootParams);
// Nested Linears
LinearLayout linearOne = new LinearLayout(this);
LinearLayout linearTwo = new LinearLayout(this);
LinearLayout linearThree = new LinearLayout(this);
LinearLayout.LayoutParams linearParamsWithWeight = new LinearLayout.LayoutParams(
0,
300);
linearParamsWithWeight.weight = 1;
linearOne.setBackgroundColor(ContextCompat.getColor(this, android.R.color.black));
linearTwo.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_red_dark));
linearThree.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_blue_dark));
linearOne.setLayoutParams(linearParamsWithWeight);
linearTwo.setLayoutParams(linearParamsWithWeight);
linearThree.setLayoutParams(linearParamsWithWeight);
rootLinearlayout.addView(linearOne);
rootLinearlayout.addView(linearTwo);
rootLinearlayout.addView(linearThree);

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.

How can I programatically create a ScrollView with RelativeLayout boxes like this?

I am trying to create an Activity with a ScrollView in it. In the ScrollView will be "boxes" (sort of like a button) that is just a bit smaller than the width of the parent view and spaced slightly apart vertically. Because the boxes will have a couple different size text in a couple areas on them, I think I need to make the out of RelativeLayouts. (I would post a picture but can't with my reputation point so hopefully this makes sense).
I tried create an XML for the activity and than programatically adding the relativeviews. I got it to work, sort of, but am having trouble with the box spacing.
My test XML looks like this...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- scrolling section -->
<ScrollView
android:layout_width="fill_parent"
android:paddingTop="5dp"
android:layout_height="0dp"
android:layout_weight="1.30"
>
<LinearLayout
android:id="#+id/llScroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
</LinearLayout>
My Activity looks like this...
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout llAccts=(LinearLayout)findViewById(R.id.llScroll);
for (int i=1;i<20;i++) {
RelativeLayout rlView = new RelativeLayout(this);
rlView.setBackgroundColor(Color.BLUE);
TextView test=new TextView(this);
test.setText("Test #"+i);
test.setTextColor(Color.WHITE);
rlView.addView(test);
llAccts.addView(rlView,new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}
I get the scrollable section, no problem. Problem is my blue "boxes" appear to be touching one another and I can't figure out how to make them look like buttons with padding left and right and between them. I tried
rlView.setPadding(20,20,20,20);
right after the setBackground color. All that appears to do is pad the text... not the RelativeViews.
Any suggestions no how to get this to work?
Thanks
===========
NEW INFORMATION:
Here is some additional information after following some suggestions and trial an error. I was also able to post a pic for easier reference.
===========
What I am trying to achieve, programmatically, is something that looks like this.
I achieved this example using the straight XML which looks like this...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- header: non-scrolling -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPDATE ALL"
android:id="#+id/btnUpdate" />
</RelativeLayout>
<!-- scrolling bottom pane -->
<ScrollView
android:layout_width="fill_parent"
android:paddingTop="5dp"
android:layout_height="0dp"
android:layout_weight="1.30"
>
<LinearLayout
android:id="#+id/llGroups"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
// individual groups start here - this section will be controlled by a database
// #1 group
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#color/blue"
android:padding="5dp"
android:clickable="true"
android:id="#+id/grp1"
>
<TextView
android:id="#+id/text1"
android:text="Item #1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/leftext1"
android:text="123.00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="30dp" />
</RelativeLayout>
// #2 group
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#color/blue"
android:padding="5dp"
android:clickable="true"
android:id="#+id/grp2"
>
<TextView
android:id="#+id/text2"
android:text="Item #2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/leftext2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/leftext2"
android:text="456.00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="30dp"
/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
I took this apart and created an XML file and and activity that will programmatically create the middle groups.
The modified XML (activity_main2) looks like this...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- header: non-scrolling -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPDATE ALL"
android:id="#+id/btnUpdate" />
</RelativeLayout>
<!-- scrolling bottom pane -->
<ScrollView
android:layout_width="fill_parent"
android:paddingTop="5dp"
android:layout_height="0dp"
android:layout_weight="1.30"
>
<LinearLayout
android:id="#+id/llGroups"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
</LinearLayout>
I started rewriting my activity code to test some of the suggestions. It currently looks like this...
public class Main2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LinearLayout llGroups=(LinearLayout)findViewById(R.id.llGroups);
for (int i=1;i<20;i++) {
RelativeLayout rlView = new RelativeLayout(this);
rlView.setBackgroundColor(Color.BLUE);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp.setMargins(10,10,10,0);
TextView test=new TextView(this);
test.setText("Test #"+i);
test.setTextColor(Color.WHITE);
rlView.addView(test);
// other textviews will go here
llGroups.addView(rlView,rlp);
}
}
}
This compiles and runs, but the setMargins is not working. My screen has the "UPDATE ALL" button at the top like it should and (19) "Text #" with a blue background, but they are full width and touching one another so it is a solid blue background.
I am getting close, but not sure how to get the margins to set correctly for the rlView relativeview (not the textviews).
Hopefully this helps explain what I am seeing now..
SOLUTION
After suggestions, and some trial and error... here is what I had to do to achieve the desired layout in case someone else is interested.
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams tvp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams tvp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
LinearLayout mTvContainer = (LinearLayout) findViewById(R.id.llAccts);
for (int i = 0; i < 20; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setBackgroundColor(Color.BLUE);
RelativeLayout rl = new RelativeLayout(this);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setPadding(5, 5, 5, 5);
tv.setText("Test #" + i);
tvp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
TextView tv2 = new TextView(this);
tv2.setTextColor(Color.WHITE);
tv2.setPadding(5, 5, 5, 5);
tv2.setText(String.valueOf(i));
tv2.setTextSize(30);
tvp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rl.addView(tv, tvp);
rl.addView(tv2,tvp2);
ll.addView(rl);
llp.setMargins(32,16,32,16);
mTvContainer.addView(ll,llp);
}
}
For each entry in the FOR, I had to use a LINEARLAYOUT to be able to set the margins properly, and in that LINEARLAYOUT I had to use a RELATIVELAYOUT to use the addRules to get the proper positioning of the TextViews.
If there is an easier way, let me know. Thanks for everyones help!!
You are using too much nested layouts needed, here is stripped version.
xml:
<ScrollView 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:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</ScrollView>
Activity code:
mTvContainer = (LinearLayout) findViewById(R.id.ll_main);
int p = (int) getResources().getDimension(R.dimen.activity_horizontal_margin);
for (int i = 0; i < 20; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setBackgroundColor(Color.BLUE);
tv.setTextColor(Color.WHITE);
tv.setPadding(p, p / 2, p, p / 2);
tv.setText("TextView " + i);
TextView tv2 = new TextView(this);
tv2.setBackgroundColor(Color.RED);
tv2.setTextColor(Color.WHITE);
tv2.setPadding(p, p / 2, p, p / 2);
tv2.setText("TextView " + i);
ll.addView(tv);
ll.addView(tv2);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(p, p / 2, p, p / 2);
mTvContainer.addView(ll, params);
}

Android. Programmatically added rows are not stretching well (TableLayout)

I have a TableLayout declared in a XML File, it will show scores, and these scores are added via rows programmatically. The problem is that the layout without any score added looks like this (As it should be):
Correct
But when a score's row is added, it looks like this:
Wrong
I can’t understand why this is happening, I would like to see the columns well stretched and there’s no apparent reason that explains this behavior. If anyone can help me i'll be very grateful.
Thanks in advance and sorry for my english.
Here is my XML and my code:
XML:
<TableLayout xmlns...
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stretchColumns="*"
android:layout_column="5"
android:id="#+id/scoresTable">
<TableRow
android:layout_gravity="center_horizontal"
android:id="#+id/titleScoresRow"
android:layout_height="42dp">
<TextView
android:id="#+id/scoresTitle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Best Scores"
android:layout_span="5"
android:gravity="center"
/>
</TableRow>
<TableRow
android:layout_gravity="center_horizontal"
android:id="#+id/firstRow"
android:layout_height="42dp">
<TextView
android:id="#+id/MODE"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="MODE"
android:gravity="center"
/>
<TextView
android:id="#+id/KANA"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="KANA"
android:gravity="center"
/>
<TextView
android:id="#+id/DIFF"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="DIFF"
android:gravity="center"
/>
<TextView
android:id="#+id/SCORE"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="SCORE"
android:gravity="center"
/>
<TextView
android:id="#+id/DATE"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="DATE"
android:gravity="center"
/>
</TableRow>
Activity:
TableLayout table = (TableLayout) findViewById(R.id.scoresTable);
createOrderedCSV(getApplicationContext(), 4, ":");
ArrayList<String> scores = readScores("OrderedScoresCSV.csv");
// Score rows
for (int i = scores.size() - 1; i >= 0; i--) {
String[] currentScore = scores.get(i).split(":");
TextView mode = new TextView(this);
mode.setText(currentScore[0]);
TextView kana = new TextView(this);
kana.setText(currentScore[2]);
TextView diff = new TextView(this);
diff.setText(currentScore[1]);
TextView score = new TextView(this);
score.setText(currentScore[4]);
TextView date = new TextView(this);
date.setText(currentScore[3]);
TableRow row = new TableRow(this);
row.addView(mode);
row.addView(kana);
row.addView(diff);
row.addView(score);
row.addView(date);
table.addView(row, new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
TableRow buttonRow = new TableRow(this);
Button eraseScores = new Button(this);
eraseScores.setWidth(200);
eraseScores.setHeight(60);
eraseScores.setText("Erase Scores");
buttonRow.setGravity(Gravity.CENTER_HORIZONTAL);
buttonRow.addView(eraseScores);
table.addView(buttonRow);
It was caused by the button row that I added at the end. It was attached to the first column.

Different view edittext in Android

When I create EditText programmatically I have no underline (in the second EditText). Like this: http://oi41.tinypic.com/2ut427d.jpg
When I create an EditText in XML everything is fine, see http://oi44.tinypic.com/nmxdnm.jpg. Where is the error?
This is my XML layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<include layout="#layout/input_title_layout" />
<TableLayout
android:id="#+id/relativeLayout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp" >
<TextView
style="#style/tvTitleStyle"
android:text="#string/diameter" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text=":" />
<EditText
android:id="#+id/diameterValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:digits="0123456780."
android:inputType="numberDecimal" />
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
And code to add EditText programatically:
final TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT, 1f);
final TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
rowParams.bottomMargin = 0;
TableLayout tableLayout = new TableLayout(context);
tableLayout.setLayoutParams(tableParams);
inputLinearLayout.addView(tableLayout);
TableRow tableRowEdit = new TableRow(context);
TextView titleTv = new TextView(context);
titleTv.setTextAppearance(context, R.style.tvTitleStyle);
titleTv.setText(context.getString(context.getResources().getIdentifier(inputTvs[i] , "string", context.getPackageName())));
TextView separatorTv = new TextView(context);
separatorTv.setGravity(Gravity.LEFT);
separatorTv.setPadding(5, 0, 5, 0);
separatorTv.setText(":");
separatorTv.setTextColor(Color.BLACK);
EditText editText = new EditText(context);
editText.setId(i);
tableRowEdit.addView(titleTv);
tableRowEdit.addView(separatorTv);
tableRowEdit.addView(editText);
tableLayout.addView(tableRowEdit);
It's hard to tell exactly what the issue might be given the code you supplied.
-Have you tried setting the layout parameters of the TableRow/TextView/EditText? The TextViews might be taking up all the visible space.
-Are you sure inputLinearLayout has been inflated?

Categories

Resources