It depends. If you are sure that you will have only a few rows, you can inflate them by adding them to the loop in TableLayout. But note that you are creating a view for each row.
With a lot of data, create a ListView and an adapter, for example, based on the CursorAdapter:
public class MyCursorAdapter extends CursorAdapter { private static final String TAG = "MyCursorAdapter"; private final int NAME_COLUMN; private final int ADDRESS_COLUMN; private final int STATE_COLUMN; public MyCursorAdapter(Context context, Cursor c) { super(context, c); NAME_COLUMN = c.getColumnIndexOrThrow("name"); ADDRESS_COLUMN = c.getColumnIndexOrThrow("address"); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.custom_row, null); MyRowViewHolder rowData = new MyRowViewHolder(); rowData.name = (TextView) view.findViewById(R.id.name); rowData.address = (TextView) view.findViewById(R.id.address); rowData.name.setText(cursor.getString(NAME_COLUMN)); rowData.address.setText(cursor.getString(ADDRESS_COLUMN)); view.setTag(rowData); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { MyRowViewHolder rowData = (MyRowViewHolder) view.getTag(); rowData.name.setText(cursor.getString(NAME_COLUMN)); rowData.address.setText(cursor.getString(ADDRESS_COLUMN)); } public static class MyRowViewHolder { TextView name; TextView address; } }
This approach does not create a view for each row. I think this is better, but more effort is needed. To get the table style, use LinearLayout for rows with layout_weight for columns
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/name" android:layout_weight="0.25" android:layout_width="0" android:layout_height="wrap_content"> </TextView> <TextView android:id="@+id/address" android:layout_weight="0.75" android:layout_width="0" android:layout_height="wrap_content"> </TextView> </LinearLayout>
In the ListView, add a header and footer if you want.
pawelzieba
source share