Dynamic TableLayout in Android
April 1, 2011 9 Comments
As my previous post for dynamic ListView is quite helpful for few readers, here I am with a similar post. Here I am creating dynamic table. The concept looks similar but the method of creation will differ. While creating a table, we will need to create the TableLayout and from the code we will be adding rows and columns. As the table rows are more, we have to put the table into a ScrollView.
Here is same example given for ListView but will provide the country and its abbreviation in a table.
//CountriesList.java package com.dynalist; public class CountriesList { public static String[] countries = { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and Mcdonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, the Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", "Virgin Islands, British", "Virgin Islands, U.s.", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" }; public static String[] abbreviations = { "AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP", "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" }; }
//MyTable.java package com.dynatable; import android.app.Activity; import android.os.Bundle; import android.util.TypedValue; import android.view.ViewGroup.LayoutParams; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.dynatable.R; public class MyTable extends Activity { /** Called when the activity is first created. */ TableLayout country_table; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); country_table=(TableLayout)findViewById(R.id.country_table); fillCountryTable(); } void fillCountryTable() { TableRow row; TextView t1, t2; //Converting to dip unit int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 1, getResources().getDisplayMetrics()); for (int current = 0; current < CountriesList.abbreviations.length; current++) { row = new TableRow(this); t1 = new TextView(this); t1.setTextColor(getResources().getColor(R.color.yellow)); t2 = new TextView(this); t2.setTextColor(getResources().getColor(R.color.dark_red)); t1.setText(CountriesList.abbreviations[current]); t2.setText(CountriesList.countries[current]); t1.setTypeface(null, 1); t2.setTypeface(null, 1); t1.setTextSize(15); t2.setTextSize(15); t1.setWidth(50 * dip); t2.setWidth(150 * dip); t1.setPadding(20*dip, 0, 0, 0); row.addView(t1); row.addView(t2); country_table.addView(row, new TableLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } } }
<?xml version="1.0" encoding="utf-8"?> <!--main.xml--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffccd0" > <TextView android:text="Countries List" android:textColor="#b3000d" android:gravity="center_vertical|center_horizontal" android:textSize="26dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:background="#ffb0b6" android:layout_marginBottom="5dip" android:typeface="sans"/> <RelativeLayout android:id="@+id/rl_country_heading" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#555555"> <TextView android:id="@+id/tv_11" android:layout_width="70dip" android:layout_height="wrap_content" android:gravity="center" android:text="Abbr" android:textStyle="normal|bold" android:textColor="#FFFFFF" android:textSize="18dip"> </TextView> <TextView android:id="@+id/tv_12" android:layout_width="150dip" android:layout_height="wrap_content" android:gravity="center" android:text="Comment" android:textStyle="normal|bold" android:textColor="#FFFFFF" android:textSize="18dip" android:layout_toRightOf="@+id/tv_11"> </TextView> </RelativeLayout> <LinearLayout android:id="@+id/ll_country" android:layout_height="fill_parent" android:layout_width="fill_parent"> <ScrollView android:id="@+id/ScrollView11" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dip"> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="0,1" android:id="@+id/country_table"> </TableLayout> </LinearLayout> </ScrollView> </LinearLayout> </LinearLayout>
package com.dynatable;
import android.app.Activity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.dynatable.R;
public class MyTable extends Activity {
/** Called when the activity is first created. */
TableLayout country_table;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
country_table=(TableLayout)findViewById(R.id.country_table);
fillCountryTable();
}
void fillCountryTable() {
TableRow row;
TextView t1, t2;
//Converting to dip unit
int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 1, getResources().getDisplayMetrics());
for (int current = 0; current < CountriesList.abbreviations.length; current++) {
row = new TableRow(this);
t1 = new TextView(this);
t1.setTextColor(getResources().getColor(R.color.yellow));
t2 = new TextView(this);
t2.setTextColor(getResources().getColor(R.color.dark_red));
t1.setText(CountriesList.abbreviations[current]);
t2.setText(CountriesList.countries[current]);
t1.setTypeface(null, 1);
t2.setTypeface(null, 1);
t1.setTextSize(15);
t2.setTextSize(15);
t1.setWidth(50 * dip);
t2.setWidth(150 * dip);
t1.setPadding(20*dip, 0, 0, 0);
row.addView(t1);
row.addView(t2);
country_table.addView(row, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
}
}
The package explorer will look like this:
Output of the example looks like this:
How can we select a row from this and delete each selected row?Please help me……….
Thanks regards
use mapping method.. Map an ID array to the rows array. and one the click of the row you can get the row id(index) from which you can retrieve the mapped ID of the data.
Now as you got the ID, you can delete or update it.
Would it be more beneficial to create a structure containing different labels and the creating an array list of said structure? I am trying to use this in order to make a table that contains information about matches for a sporting event. So each column will have something like the team date venue. Do you think that would be better than having parallel arrays and would it work with the method of creating a dynamic table you have provided?
How to handle onClickListener in this case…I want to click on a TableRow and listener should be handled and value should be shown in form of Toast Message…How can I achieve this ??
Tried this but can’t see the list. The headers are created and visible, but the scrollable table below that is not… What am I doing wrong?
package in.wptrafficanalyzer.listviewwithimagesandtext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
“India”,
“Pakistan”,
“Sri Lanka”,
“China”,
“Bangladesh”,
“Nepal”,
“Afghanistan”,
“North Korea”,
“South Korea”,
“Japan”
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.india,
R.drawable.pakistan,
R.drawable.srilanka,
R.drawable.china,
R.drawable.bangladesh,
R.drawable.nepal,
R.drawable.afghanistan,
R.drawable.nkorea,
R.drawable.skorea,
R.drawable.japan
};
// Array of strings to store currencies
String[] currency = new String[]{
“Indian Rupee”,
“Pakistani Rupee”,
“Sri Lankan Rupee”,
“Renminbi”,
“Bangladeshi Taka”,
“Nepalese Rupee”,
“Afghani”,
“North Korean Won”,
“South Korean Won”,
“Japanese Yen”
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap> aList = new ArrayList<HashMap>();
for(int i=0;i<10;i++){
HashMap hm = new HashMap();
hm.put(“txt”, “Country : ” + countries[i]);
hm.put(“cur”,”Currency : ” + currency[i]);
hm.put(“flag”, Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { “flag”,”txt”,”cur” };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
TextView t3 = (TextView) findViewById(R.id.t1);
t3.setText(
Html.fromHtml( “http://www.yahoo.com” ));
t3.setMovementMethod(LinkMovementMethod.getInstance());
listView.setAdapter(adapter);
}
}
how to add hyperlink in above code
I have created a table layout dynamically with areaId and areaName and if i wish to have a search bar above the table to search a particular area so that it displays only that record with the areaName typed in search bar …..how can i do that???
I have created a table layout dynamically with two fields id and name, and now i want to implement a search bar above that table to display only particular records according to the name specified in search bar…how can i do that?
Can I implement Swipe refresh with this tutorial?