private TableLayout mTableLayout;
mTableLayout = (TableLayout) findViewById( R.id.tableInvoices );
mTableLayout.setStretchAllColumns( true );
public void loadData(){
gross = sharedPreferences.getFloat( "Gross", 0 );
float weight = sharedPreferences.getFloat( "weight", 0 );
c = Calendar.getInstance();`enter code here`
SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yy" );
String strDate = sdf.format( c.getTime() );
SimpleDateFormat sd1f = new SimpleDateFormat( "hh:mm" );
String strtime = sd1f.format( c.getTime() );
info = new Model_Info( weight, strDate, strtime );
detail.add( 0,info );
int rows = detail.size();
//Model_Info info = null;
mTableLayout.removeAllViews();
for (int i = 0; i <rows; i++) {
info = detail.get( i );
if (info.weight == 0.000){
Toast.makeText( context, "Invalid weight", Toast.LENGTH_SHORT ).show();
} else {
// data columns
tv = new TextView( this );
tv.setLayoutParams( new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT ) );
tv.setGravity( Gravity.LEFT );
tv.setPadding( 5, 0, 0, 0 );
tv.setBackgroundResource( R.drawable.table_border );
tv.setText( String.valueOf( i+1 ) );
tv.setTextSize( TypedValue.COMPLEX_UNIT_PX,textSize );
tv.setTextColor( Color.parseColor( "#000000" ) );
tv2 = new TextView( this );
tv2.setLayoutParams( new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT ) );
tv2.setGravity( Gravity.LEFT );
tv2.setPadding( 5, 0, 0, 0 );
tv2.setBackgroundResource( R.drawable.table_border );
tv2.setTextColor( Color.parseColor( "#000000" ) );
tv2.setText( df.format( info.weight ) );
tv2.setTextSize( TypedValue.COMPLEX_UNIT_PX, textSize );
tv3 = new TextView( this );
tv3.setLayoutParams( new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT ) );
tv3.setGravity( Gravity.LEFT );
tv3.setPadding( 5, 0, 0, 0 );
tv3.setBackgroundColor( Color.parseColor( "#ffffff" ) );
tv3.setBackgroundResource( R.drawable.table_border );
tv3.setTextColor( Color.parseColor( "#000000" ) );
tv3.setText( info.date + " " + info.time );
tr_total.setText( String.valueOf( df.format( Total_Weight() ) ) );
tv3.setTextSize( TypedValue.COMPLEX_UNIT_PX, textSize );
// add table row
final TableRow tr = new TableRow( this );
tr.setId( rows + 1 );
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT );
trParams.setMargins( 0, 0, 0, 0 );
tr.setPadding( 0, 0, 0, 0 );
tr.setLayoutParams( trParams );
tr.addView( tv );
tr.addView( tv2 );
tr.addView( tv3 );
final View vline = new View( this );
vline.setLayoutParams( new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 0 ) );
mTableLayout.addView( vline );
mTableLayout.addView( tr, trParams ); } }}
使用此格式将数据从 json 插入到 tablelayout。您的表格将看起来像我附上的图像..