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.

xml

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <TableLayout
        android:id="@+id/calendar"
        android:layout_marginTop="1dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </TableLayout>
</LinearLayout>

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
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}

@Override
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]