Practical No 6
Q Write A Program to display 10 Students Basic Information In a Table form Using Table Layout
Activity_main.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"
android:padding="16dp">
<TableLayout
android:id="@+id/studentTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
android:padding="10dp"
android:layout_gravity="center">
<!-- Table Header -->
<TableRow>
<TextView
android:text="Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textStyle="bold"
android:gravity="center"/>
<TextView
android:text="Age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textStyle="bold"
android:gravity="center"/>
<TextView
android:text="Grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textStyle="bold"
android:gravity="center"/>
</TableRow>
</TableLayout>
</LinearLayout>
Main.Activity.java
package com.example.pr6;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String[] studentNames = {
"John Doe", "Jane Smith", "Sam Wilson", "Lucy Brown", "Tom Harris",
"Emma Green", "Chris Lee", "Anna White", "James Black", "Sophia Clark"
};
String[] studentAges = {
"20", "21", "22", "20", "23", "22", "21", "20", "22", "21"
};
String[] studentGrades = {
"A", "B", "A", "C", "B", "A", "B", "A", "C", "B"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableLayout tableLayout = findViewById(R.id.studentTable);
for (int i = 0; i < studentNames.length; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView nameTextView = new TextView(this);
nameTextView.setText(studentNames[i]);
nameTextView.setPadding(10, 10, 10, 10);
nameTextView.setGravity(View.TEXT_ALIGNMENT_CENTER);
row.addView(nameTextView);
TextView ageTextView = new TextView(this);
ageTextView.setText(studentAges[i]);
ageTextView.setPadding(10, 10, 10, 10);
ageTextView.setGravity(View.TEXT_ALIGNMENT_CENTER);
row.addView(ageTextView);
TextView gradeTextView = new TextView(this);
gradeTextView.setText(studentGrades[i]);
gradeTextView.setPadding(10, 10, 10, 10);
gradeTextView.setGravity(View.TEXT_ALIGNMENT_CENTER);
row.addView(gradeTextView);
tableLayout.addView(row);