Android Table Cells Border - java

This xml code below gives me a proper border around my table cells
<TableRow android:background="#cdcdcd" >
<TextView android:text="1st Column" android:background="#ffffff" android:layout_margin="2dip"/>
<TextView android:text="2nd Column" android:background="#ffffff" android:layout_margin="2dip"/>
<TextView android:id="#+id/amount" android:background="#ffffff" android:layout_margin="2dip" android:text="3rd col"/>
</TableRow>
But when i try to do it programmatically it is doesn't work here is my code:
dataTable = (TableLayout)findViewById(R.id.data_table);
TableRow tr=new TableRow(this);
counter++;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.setMargins(2,2, 2, 2);
TextView tv= new TextView(this);
tv.setLayoutParams(lp);
tv.setText("text"+counter);
tv.setBackgroundColor(Color.parseColor("#ffffff"));
counter++;
TextView cb= new TextView(this);
cb.setLayoutParams(lp);
cb.setText("text"+counter);
counter++;
TextView ib= new TextView(this);
ib.setText("text"+counter);
ib.setLayoutParams(lp);
tr.setBackgroundColor(Color.parseColor("#cdcdcd"));
tr.setPadding(2, 2, 2, 2);
tr.addView(tv);
tr.addView(cb);
tr.addView(ib);
dataTable.addView(tr,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
Every thing works except for the borders and when i set "tv.setLayoutParams(lp);" the parameters the column disappears.

Try to add the view by calling
addView(View child, int index, ViewGroup.LayoutParams params)
Also, try to create a new LayoutParams instance for each view

Related

How can I make a dynamically generated tablelayout scrollable?

I have 3 fragments inside an Activity and in two of the fragments I have a hardcoded TableLayout inside a ConstraintLayout, the headers and rows of the tables are dynamically generated with information from a MySQL server. Given its dynamic nature, the table is able to overflow the page and I want it to be scrollable.
There are already multiple questions on StackOverflow where people have wanted a scrollable table, but in the questions, the tables and their data are hardcoded (don't know if that is relevant or not). I have tried the solutions proposed in those questions but they don't work on my table. The solutions are generally to either wrap the TableLayout in a ScrollView or to use android:isScrollContainer="1" neither of which have worked for me.
TableLayout inside ScrollView. The ScrollView is there for testing, normally it is just the TableLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewProductLocFragment">
<!-- Rest of the fragment -->
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:layout_weight="1"
android:scrollbars="none"
app:layout_constraintBottom_toTopOf="#+id/menuBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:stretchColumns="*"
app:layout_constraintBottom_toTopOf="#+id/menuBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view">
</TableLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Here is the code that fills the table.
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_view_product_main, container, false);
initializeTableLayout(view);
fillTable(((ViewProductActivity)getActivity()).pallets);
return view;
}
private void fillTable(PalletsResult pallets)
{
Integer count = 0;
for(Pallet pallet : pallets.getPallets()) {
String barcode = pallet.getBarcode();
String location = pallet.getCode();
Integer quantity = pallet.getQuantity();
TableRow tableRow = new TableRow(getContext());
if (count % 2 != 0) {
tableRow.setBackgroundColor(getResources().getColor(R.color.lightGrey));
}
tableRow.setId(View.generateViewId());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
TextView labelBarcode = new TextView(getContext());
labelBarcode.setId(View.generateViewId());
labelBarcode.setGravity(Gravity.CENTER);
labelBarcode.setTextColor(getResources().getColor(R.color.standardTextColor));
labelBarcode.setTextSize(18);
labelBarcode.setText(barcode);
tableRow.addView(labelBarcode);
TextView labelLocation = new TextView(getContext());
labelLocation.setId(View.generateViewId());
labelLocation.setGravity(Gravity.CENTER);
labelLocation.setTextColor(getResources().getColor(R.color.standardTextColor));
labelLocation.setTextSize(18);
labelLocation.setText(location);
tableRow.addView(labelLocation);
TextView labelQuantity = new TextView(getContext());
labelQuantity.setId(View.generateViewId());
labelQuantity.setGravity(Gravity.CENTER);
labelQuantity.setTextColor(getResources().getColor(R.color.standardTextColor));
labelQuantity.setTextSize(18);
labelQuantity.setText(quantity.toString());
tableRow.addView(labelQuantity);
tableLayout.addView(tableRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
count++;
}
}
private void initializeTableLayout(View view)
{
tableLayout = view.findViewById(R.id.tableLayout);
TableRow tr_head = new TableRow(getContext());
tr_head.setId(View.generateViewId());
tr_head.setBackgroundColor(getResources().getColor(R.color.lightGrey));
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
));
TextView label_barcode = new TextView(getContext());
label_barcode.setId(View.generateViewId());
label_barcode.setText("BARCODE");
label_barcode.setTextSize(20);
label_barcode.setTextColor(Color.BLACK);
label_barcode.setGravity(Gravity.CENTER);
tr_head.addView(label_barcode);// add the column to the table row here
TextView label_location = new TextView(getContext());
label_location.setId(View.generateViewId());// define id that must be
unique
label_location.setText("LOCATION"); // set the text for the header
label_location.setTextSize(20);
label_location.setTextColor(Color.BLACK); // set the color
label_location.setGravity(Gravity.CENTER);
tr_head.addView(label_location); // add the column to the table row here
TextView label_quantity = new TextView(getContext());
label_quantity.setId(View.generateViewId());// define id that must be
unique
label_quantity.setText("QTY"); // set the text for the header
label_quantity.setTextSize(20);
label_quantity.setTextColor(Color.BLACK); // set the color
label_quantity.setGravity(Gravity.CENTER);
tr_head.addView(label_quantity); // add the column to the table row here
tableLayout.setScrollContainer(true);
tableLayout.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
This creates a table that runs off the end of the page and that can't be scrolled.
There is a fair bit of other code that I didn't post in regards to the Activity containing the fragments and what not. Let me know if you want any of that.
Thanks for any help.
Update: I implemented a similar table elsewhere in my app and it worked just fine with the code posted in my examples. This means that the problem I am having is realted to the table being in a fragment and not an activity. I will post some of my fragment code later.
I have tried implementing your code over an Activity. I am posting my Activity and XML code for your reference, can you see what you are missing in your complete code so that this can be helpful.
MainActivity.java
public class MainActivity extends Activity {
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeTableLayout();
}
#Override
protected void onResume() {
super.onResume();
fillTable();
}
private void fillTable() {
Integer count = 0;
for (int i = 0; i < 100; i++) {
String barcode = "#0000000000";
String location = "Location";
Integer quantity = 1;
TableRow tableRow = new TableRow(MainActivity.this);
if (count % 2 != 0) {
tableRow.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
}
tableRow.setId(View.generateViewId());
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
TextView labelBarcode = new TextView(MainActivity.this);
labelBarcode.setId(View.generateViewId());
labelBarcode.setGravity(Gravity.CENTER);
labelBarcode.setTextColor(getResources().getColor(R.color.colorAccent));
labelBarcode.setTextSize(18);
labelBarcode.setText(barcode);
tableRow.addView(labelBarcode);
TextView labelLocation = new TextView(MainActivity.this);
labelLocation.setId(View.generateViewId());
labelLocation.setGravity(Gravity.CENTER);
labelLocation.setTextColor(getResources().getColor(R.color.colorAccent));
labelLocation.setTextSize(18);
labelLocation.setText(location);
tableRow.addView(labelLocation);
TextView labelQuantity = new TextView(MainActivity.this);
labelQuantity.setId(View.generateViewId());
labelQuantity.setGravity(Gravity.CENTER);
labelQuantity.setTextColor(getResources().getColor(R.color.colorAccent));
labelQuantity.setTextSize(18);
labelQuantity.setText(quantity.toString());
tableRow.addView(labelQuantity);
tableLayout.addView(tableRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
count++;
}
}
private void initializeTableLayout() {
tableLayout = this.findViewById(R.id.tableLayout);
TableRow tr_head = new TableRow(MainActivity.this);
tr_head.setId(View.generateViewId());
tr_head.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
tr_head.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView label_barcode = new TextView(MainActivity.this);
label_barcode.setId(View.generateViewId());
label_barcode.setText("BARCODE");
label_barcode.setTextSize(20);
label_barcode.setTextColor(Color.BLACK);
label_barcode.setGravity(Gravity.CENTER);
tr_head.addView(label_barcode);// add the column to the table row here
TextView label_location = new TextView(MainActivity.this);
label_location.setId(View.generateViewId());// define id that must be unique
label_location.setText("LOCATION"); // set the text for the header
label_location.setTextSize(20);
label_location.setTextColor(Color.BLACK); // set the color
label_location.setGravity(Gravity.CENTER);
tr_head.addView(label_location); // add the column to the table row here
TextView label_quantity = new TextView(MainActivity.this);
label_quantity.setId(View.generateViewId());// define id that must be unique
label_quantity.setText("QTY"); // set the text for the header
label_quantity.setTextSize(20);
label_quantity.setTextColor(Color.BLACK); // set the color
label_quantity.setGravity(Gravity.CENTER);
tr_head.addView(label_quantity); // add the column to the table row here
tableLayout.setScrollContainer(true);
tableLayout.addView(tr_head, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:layout_weight="1"
android:scrollbars="none">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:stretchColumns="*"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"></TableLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
I have manually added 100 dummy rows to test its scroll behaviour and would like to inform you that it is exactly working as it should. There could be a problem in your Activity or Fragment parent code which is preventing the table from scrolling.
You can use TableView library to make your Table scrollable with dynamic data. The link is given below:-
https://github.com/evrencoskun/TableView

Create Horizontal and Vertical Scroll View Dynamically Android

In my project i managed to display the database in the form of rows and columns of edit Texts and text Views.But the as the number of rows and columns increase it is not possible to view the added data , they dont fit into the screen.
so i think i needed a horizontal scrollview and a vertical scrollview for viewing entire rows and columns. Below
is my code kindly help me how to achieve this.
Please do help me thanks in advance
xml code is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TableLayout
android:layout_width="wrap_content"
android:stretchColumns="0,1,2,3,4,5"
android:id="#+id/maintable"
android:layout_height="wrap_content"
android:layout_weight="1.0">
</TableLayout>
</LinearLayout>
The following is the code for page where i wanna display my rows and columns
public class ViewActivity extends Activity {
EditText col1;
EditText col2;
TextView Id;
EditText col4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
ScrollView sv = new ScrollView(this);
HorizontalScrollView hs =new HorizontalScrollView(this);
TableLayout tl = (TableLayout) findViewById(R.id.maintable);
//CREATING A LIST OF HEADINGS
TableRow tr1 = new TableRow(this);
tr1.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ));
Id = new TextView(this);
Id.setText("COL1");
tr1.addView(Id);
Id = new TextView(this);
Id.setText("COL2");
tr1.addView(Id);
Id = new TextView(this);
Id.setText("COL3");
tr1.addView(Id);
Id = new TextView(this);
Id.setText("Rssi");
tr1.addView(COL4);
Id = new TextView(this);
Id.setText("Delete");
tr1.addView(COL5);
Id = new TextView(this);
Id.setText("Update");
tr1.addView(COL6);
hs.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
tl.addView(tr1,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// CREATING ROWS AND COLUMNS DYNAMICALLY
final DBclass entry = new DBclass(ViewActivity.this);
entry.open();
Cursor c = entry.getAllRecords();
int count =0;
if(c.moveToFirst()){
do{
TableRow tr = new TableRow(this);
tr.setId(count);
tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ));
/* CODE FOR
COLUMNS DISPLAYED IN THE FORM OF
EDITTEXTS AND TEXTVIEWS
*/
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
count++;
}while(c.moveToNext());
}
}
I'm fairly sure you could simply put your TableLayout inside a ScrollView to solve this problem. No need to fiddle with adding Views programatically, just predefine it in the XML layout resource. Like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_width="wrap_content"
android:stretchColumns="0,1,2,3,4,5"
android:id="#+id/maintable"
android:layout_height="wrap_content"
android:layout_weight="1.0">
</TableLayout>
</ScrollView>
</LinearLayout>
Keep in mind ScrollView is vertical, so you'd need to add a HorizontalScrollView in there to add horizontal scrolling as well.

Alignment issue with contents of table row generated programmatically

I have created an activity in which I want to programmatically generate rows in a table. The table will have a checkbox, imageview, and 2 textviews in every rows. The rows are getting generated, but the alignment of the contents in the rows are not correct.
The activity code:
public class PlanTripActivity extends ActionBarActivity {
int tableRowCount = 0;
TableLayout plan_a_trip_table;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_trip);
plan_a_trip_table = (TableLayout) findViewById(R.id.plan_a_trip_table);
planTripBody("", "Test Name Type",
"P1");
}
//table body
public void planTripBody(String imagename, String nameType,
String placeId) {
tableRowCount = tableRowCount + 1;
// ----------------plan_a_trip_table table
// body------------------------------------------
TableRow plan_trip_tr_data = new TableRow(this);
plan_trip_tr_data.setId(10);
//plan_trip_tr_data.setBackgroundResource(R.drawable.grey_list_bg);
plan_trip_tr_data.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// select checkbox
final CheckBox select_checkbox = new CheckBox(this);
select_checkbox.setId(20);
select_checkbox.setTextColor(Color.BLACK);
select_checkbox.setGravity(Gravity.CENTER);
select_checkbox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
plan_trip_tr_data.addView(select_checkbox);
// image
final ImageView place_imageview = new ImageView(this);
place_imageview.setId(20);
// test_name.setText(parser.getValue(e, KEY_SETNAME));
//place_imageview.setPadding(5, 5, 5, 5);
place_imageview.setImageResource(R.drawable.planatrip);
plan_trip_tr_data.addView(place_imageview);// add the column to
// the table row
// here
// Type
final TextView name_type = new TextView(this);
name_type.setId(21);// define id that must be unique
// no_of_types.setText(parser.getValue(e, KEY_RIGHTMARKS)); // set
// the text for the header
name_type.setText(Html.fromHtml(nameType));
name_type.setTextColor(Color.BLACK); // set the color
name_type.setPadding(5, 5, 5, 5); // set the padding (if
// required)
name_type.setGravity(Gravity.LEFT);
name_type.setTextSize(18);
plan_trip_tr_data.addView(name_type); // add the column
// to
// the table row
// here
// ID
final TextView place_id = new TextView(this);
place_id.setId(21);// define id that must be unique
// total_amount.setText(parser.getValue(e, KEY_WRONGMARKS)); // set
// the text for the header
place_id.setText(placeId);
place_id.setTextColor(Color.BLACK); // set the color
place_id.setPadding(5, 5, 5, 5); // set the padding (if
// required)
place_id.setGravity(Gravity.CENTER);
place_id.setTextSize(10);
plan_trip_tr_data.addView(place_id); // add the column
// to the
// table row here
plan_a_trip_table.addView(plan_trip_tr_data,
new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// ----------------------On click name_type
name_type.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!select_checkbox.isChecked()) {
select_checkbox.setChecked(true);
} else {
select_checkbox.setChecked(false);
}
}
});
// ----------------------On click customer_name
}
}
The layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<TextView
android:id="#+id/city_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="City name"
android:textSize="20sp" />
<ImageView
android:id="#+id/update_indicator_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/presence_busy"
android:layout_marginLeft="10dp"/>
</TableRow>
<TableLayout
android:id="#+id/plan_a_trip_table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableRow1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:stretchColumns="0,1,2,3">
</TableLayout>
<Button
android:id="#+id/plan_a_trip_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/plan_a_trip_table"
android:layout_centerHorizontal="true"
android:text="Plan Trip"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
The output:
Expected output:
What should I do to center the checkbox, imageview and textboxes in the same line such that they do not look haphazard as in the above output?
In your code,you also need to align your TableRow in CENTER,as
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
rowParams.gravity = Gravity.CENTER;
And also set layoutParams for all the child Views.
i.e. Simply,Try to change planTripBody function with below code,it will work.
public void planTripBody(String imagename, String nameType,
String placeId) {
tableRowCount = tableRowCount + 1;
// ----------------plan_a_trip_table table
// body------------------------------------------
TableRow plan_trip_tr_data = new TableRow(this);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
rowParams.gravity = Gravity.CENTER;
plan_trip_tr_data.setLayoutParams(rowParams);
plan_trip_tr_data.setId(10);
//plan_trip_tr_data.setBackgroundResource(R.drawable.grey_list_bg);
plan_trip_tr_data.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams innerParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
// select checkbox
final CheckBox select_checkbox = new CheckBox(this);
select_checkbox.setId(20);
select_checkbox.setLayoutParams(innerParams);
select_checkbox.setTextColor(Color.BLACK);
select_checkbox.setGravity(Gravity.CENTER);
select_checkbox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
plan_trip_tr_data.addView(select_checkbox);
// image
final ImageView place_imageview = new ImageView(this);
place_imageview.setId(20);
place_imageview.setLayoutParams(innerParams);
// test_name.setText(parser.getValue(e, KEY_SETNAME));
//place_imageview.setPadding(5, 5, 5, 5);
place_imageview.setImageResource(R.drawable.planatrip);
plan_trip_tr_data.addView(place_imageview);// add the column to
// the table row
// here
// Type
final TextView name_type = new TextView(this);
name_type.setLayoutParams(innerParams);
name_type.setId(21);// define id that must be unique
// no_of_types.setText(parser.getValue(e, KEY_RIGHTMARKS)); // set
// the text for the header
name_type.setText(Html.fromHtml(nameType));
name_type.setTextColor(Color.BLACK); // set the color
name_type.setPadding(5, 5, 5, 5); // set the padding (if
// required)
name_type.setGravity(Gravity.LEFT);
name_type.setTextSize(18);
plan_trip_tr_data.addView(name_type); // add the column
// to
// the table row
// here
// ID
final TextView place_id = new TextView(this);
place_id.setLayoutParams(innerParams);
place_id.setId(21);// define id that must be unique
// total_amount.setText(parser.getValue(e, KEY_WRONGMARKS)); // set
// the text for the header
place_id.setText(placeId);
place_id.setTextColor(Color.BLACK); // set the color
place_id.setPadding(5, 5, 5, 5); // set the padding (if
// required)
place_id.setGravity(Gravity.CENTER);
place_id.setTextSize(10);
plan_trip_tr_data.addView(place_id); // add the column
// to the
// table row here
plan_a_trip_table.addView(plan_trip_tr_data,
new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// ----------------------On click name_type
name_type.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!select_checkbox.isChecked()) {
select_checkbox.setChecked(true);
} else {
select_checkbox.setChecked(false);
}
}
});
// ----------------------On click customer_name
}
EDIT
You need to set android:gravity="center_vertical" property to TableRow to align its child vertically center.
And Use TableRow height as android:layout_height="match_parent"
and set Padding to table row as android:paddingTop="10dp",do not set Margin to Textview as
So Change your layout to below code.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:paddingTop="10dp"
android:gravity="center_vertical"
android:layout_centerHorizontal="true" >
<TextView
android:id="#+id/city_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City name"
android:textSize="20sp" />
<ImageView
android:id="#+id/update_indicator_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/presence_busy"
android:layout_marginLeft="10dp"/>
</TableRow>
<TableLayout
android:id="#+id/plan_a_trip_table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableRow1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:stretchColumns="0,1,2,3">
</TableLayout>
<Button
android:id="#+id/plan_a_trip_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/plan_a_trip_table"
android:layout_centerHorizontal="true"
android:text="Plan Trip"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>

Creating LinearLayout Programmatically/Dynamically with Multiple Views

I have a hierarchy that is like this:
LinearLayout(horizontal)
ImageView
LinearLayout(vertical)
TextView
TextView
TextView
TextView
I want to be able to add the hierarchy above through iteration as long as there is data that could be obtained from the database(using Parse)
I have tried putting up the ImageView and LinearLayout under the parent LinearLayout but it doesn't seem to work. Here is my code in MainActivity.Java:
LinearLayout LL_Outer = (LinearLayout) findViewById(R.id.new_linearLayoutOuter);
LL_Outer.setOrientation(LinearLayout.VERTICAL); // set orientation
LL_Outer.setBackgroundColor(color.white); // set background
// set Layout_Width and Layout_Height
LinearLayout.LayoutParams layoutForOuter = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LL_Outer.setLayoutParams(layoutForOuter);
LinearLayout LL_Inner = (LinearLayout) findViewById(R.id.new_linearLayoutInner);
LL_Inner.setOrientation(LinearLayout.HORIZONTAL);
LL_Inner.setBackgroundColor(color.white);
LinearLayout.LayoutParams layoutForInner = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LL_Inner.setLayoutParams(layoutForInner);
//LL_Outer.addView(LL_Inner);
ImageView IV = (ImageView) findViewById(R.id.new_imageViewPP);
//IV.getLayoutParams().height = 55;
//IV.getLayoutParams().width = 55;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(14, 12, 0, 0);
params.height = 55;
params.weight = 55;
IV.setBackgroundColor(color.black);
IV.setLayoutParams(params);
LL_Inner.addView(IV);
LL_Outer.addView(LL_Inner);
I don't know where I went wrong as my code did not prompt any error. Please help.
EDIT: I have edited the Orientations accordingly and when I run the app, it stops working. And prompts an error in LogCat saying "The specified child already has a parent. You must call removeView() on the child's parent first.
Here's my XML:
<LinearLayout
android:id="#+id/new_linearLayoutOuter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<ImageView
android:id="#+id/new_imageViewPP"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="14dp"
android:layout_marginTop="12dp"
android:background="#color/black"
android:contentDescription="#string/pp" />
<LinearLayout
android:id="#+id/new_linearLayoutInner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical" >
<TextView
android:id="#+id/new_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/movie_title"
android:paddingTop="10dp"
android:paddingLeft="7dp"
android:textSize="15sp" /> <!-- Title of the movie -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/review_by"
android:paddingTop="3dp"
android:paddingLeft="7dp"
android:textSize="12sp" /> <!-- By -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/movie_stars"
android:paddingTop="3dp"
android:paddingLeft="7dp"
android:textSize="12sp" /> <!-- Rating and date -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sample_string"
android:maxLines="5"
android:scrollbars="vertical"
android:paddingTop="10dp"
android:paddingLeft="7dp"
android:textSize="12sp"
android:layout_gravity="center_vertical|right" /> <!-- Review content -->
</LinearLayout>
</LinearLayout>
You want that hierarchy programmatically.
- LinearLayout(horizontal)
- ImageView
- LinearLayout(vertical)
- TextView
- TextView
- TextView
- TextView
Ok lets start with Parent LinearLayout
LinearLayout parent = new LinearLayout(context);
parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.HORIZONTAL);
//children of parent linearlayout
ImageView iv = new ImageView(context);
LinearLayout layout2 = new LinearLayout(context);
layout2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout2.setOrientation(LinearLayout.VERTICAL);
parent.addView(iv);
parent.addView(layout2);
//children of layout2 LinearLayout
TextView tv1 = new TextView(context);
TextView tv2 = new TextView(context);
TextView tv3 = new TextView(context);
TextView tv4 = new TextView(context);
layout2.addView(tv1);
layout2.addView(tv2);
layout2.addView(tv3);
layout2.addView(tv4);
And you are done :)
The problem is because the views are already added to the layout in the XML file. Then you findViewById (find them) and try to add them to the layout again. That is why the app crashes complaining that, view already has a parent and you can't add it again.
In the XML File LinearLayout already has child view. So there is not need to add them in code.
i suggest you to remove the xml file and just use full code on the java side. you can add the views programatically from the java side. this one from xtreemdeveloper but i change few line for the parent layout.
// remove this params set it up below
parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// change the code above into
.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
addContentView(parent,layoutParams);
// end of my change
it will look like this in full code =
LinearLayout parent = new LinearLayout(context);
// remove this params set it up below
parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// change the code above into
.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
addContentView(parent,layoutParams);
// end of my change
parent.setOrientation(LinearLayout.HORIZONTAL);
//children of parent linearlayout
ImageView iv = new ImageView(context);
LinearLayout layout2 = new LinearLayout(context);
layout2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout2.setOrientation(LinearLayout.VERTICAL);
parent.addView(iv);
parent.addView(layout2);
//children of layout2 LinearLayout
TextView tv1 = new TextView(context);
TextView tv2 = new TextView(context);
TextView tv3 = new TextView(context);
TextView tv4 = new TextView(context);
layout2.addView(tv1);
layout2.addView(tv2);
layout2.addView(tv3);
layout2.addView(tv4);

Alignment of imageview in tablelayout

This should be easy, how can I align the star in the middle. I'm adding the top header textviews and stars dynamically in code. I tried setting gravity on the imageview did not work.
UPDATE: I added iv.setScaleType(ImageView.ScaleType.FIT_START) now star aligns to left
<?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="fill_parent" xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads">
<TableLayout
android:id="#+id/TableAch"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:layout_alignParentTop="true"
android:shrinkColumns="*"
android:stretchColumns="*"
>
<TableRow
android:id="#+id/RowAchTitle"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center_horizontal"
>
<TextView
android:id="#+id/ViewAchTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Achievements"
android:gravity="center"
android:layout_span="6">
</TextView>
</TableRow>
<TableRow
android:id="#+id/RowAchHeader"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:weightSum="6"
>
</TableRow>
</TableLayout>
</RelativeLayout>
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acheivements);
tbLayout = (TableLayout) this.findViewById(R.id.TableAch);
rowHeader = (TableRow) this.findViewById(R.id.RowAchHeader);
FlurryAgent.logEvent("Achievements");
TableRow.LayoutParams tableRowParams=
new TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 0, 0, 5);
TableRow.LayoutParams params = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT);
params.weight = 1;
params.gravity= Gravity.CENTER;
int fontSize = 12;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(" ");
tv.setTextSize(fontSize);
rowHeader.addView(tv); //This is blank top left corner
for (Level level : Level.values()) { //Then we add all the headers for games
tv = new TextView(this);
tv.setText("EASY");
tv.setTextSize(fontSize);
tv.setLayoutParams(params);
rowHeader.addView(tv);
}
//Next we add the levels for each game, putting a pass image where passed
for (Games game : Games.values()) {
TableRow newRow = new TableRow(this);
newRow.setLayoutParams(tableRowParams);
String[] words = game.name().split("(?=[A-Z])");
String name = "";
for (String word : words) {
if(word.length() < 1) continue;
name += word + "\n";
}
tv = new TextView(this);
tv.setTextSize(fontSize);
tv.setText(name);
tv.setLayoutParams(params);
newRow.addView(tv);
newRow.setWeightSum(6);
for (Level level : Level.values()) {
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_START);
iv.setLayoutParams(params);
tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText("EASY");
tv.setTextSize(fontSize);
if( acheivements.getPassed(level, game) )//has achievement
{
iv.setImageResource(R.drawable.star_gold_full_small);
}
else {
iv.setImageResource(R.drawable.star_gold_empty_small);
}
newRow.addView(tv);
}
tbLayout.addView(newRow);
}
setupAds(true);
}
You should do this:
TableRow.LayoutParams params = new TableRow.LayoutParams(0,WRAP_CONTENT);
you should have layout params of tablerow for textviews.
then in this params you should add weight.
params.weight = 1;
params.gravity = GRAVITY.CENTER;
and your table row should have gravity "Center" for its content (not layout gravity).
Try do this:
for (Games game : Games.values()) {
TableRow newRow = new TableRow(this);
newRow.setLayoutParams(tableRowParams);
TableRow.LayoutParams params2 = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT);
params2.weight = .8f;
params2.gravity= Gravity.CENTER;
String[] words = game.name().split("(?=[A-Z])");
String name = "";
for (String word : words) {
if(word.length() < 1) continue;
name += word + "\n";
}
tv = new TextView(this);
tv.setTextSize(fontSize);
tv.setText(name);
tv.setLayoutParams(params2);
newRow.addView(tv);
newRow.setWeightSum(6);
for (Level level : Level.values()) {
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.setAdjustViewBounds(true);
iv.setLayoutParams(params);
tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText("EASY");
tv.setTextSize(fontSize);
if( acheivements.getPassed(level, game) )//has achievement
{
iv.setImageResource(R.drawable.star_gold_full_small);
}
else {
iv.setImageResource(R.drawable.star_gold_empty_small);
}
newRow.addView(tv);
}
tbLayout.addView(newRow);
}
In this code i have created new layout params as params2 because the textview was using weight of 1 so that your images were little right sided. i had used .8f weight for the names so now its working ok. so do as per your req.
Hope it Helps!!
Here's a minimal solution based on the above comments:
<ImageView
android:scaleType="fitCenter"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#mipmap/cross" />
The first half containes the attributes that seem to be necessary to solve the problem.

Categories

Resources