TableLayout in Program

This topic is for TableLayout for Android.
TableLayout is table like, and one of Android Layout parts.
Of course, we can layout of table layout including table, row, cell in xml.
But, I would like to change parameters according to device, especially size.

Next is idea.


I made blank TableLayout in xml.(fragment_calendar.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

Add row and cell programmatically

This is a fragment example.
Get TableLayout using findViewById
To add row, creating TableRow class. And it is added to table.
The key point is TableLayout.LayoutParams
To arrange layout of Table related, we should use this parameter.
If not, row and cell aren’t displayed.

public class CalendarFragment extends Fragment
public void onCreate(Bundle savedInstanceState)

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View v = inflater.inflate(R.layout.fragment_calendar, container, false);

for ( int i=0; i < 6; i++ ) { TableRow tr= new TableRow(getActivity().getApplicationContext()); TableLayout.LayoutParams tr_params = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); tr_params.setMargins(0, (int)(2 * density), 0, 0); tr.setLayoutParams(tr_params); for ( int j=0; j < 7; j++ ) { TextView tile = new TextView(getActivity().getApplicationContext()); TableRow.LayoutParams td_params = new TableRow.LayoutParams(tile_width, tiel_height); tile.setLayoutParams(td_params); td_params.setMargins(1, 0, 0, 0); tr.addView(tile); } table.addView(tr); } return v; } } [/java]