728x90

안드로이드 스튜디오에서 TableLayout을 이용해 간단하게 표처럼 만드는 방법입니다.

 

TableLayout을 생성하면 하위에 TableRow도 생성이 됩니다. 이제 이 TableRow안에 View를 추가하면 됩니다.

소스코드는 아래와 같습니다. 

<TableLayout
        android:layout_width="1187dp"
        android:layout_height="733dp"
        android:layout_marginStart="44dp"
        android:layout_marginLeft="44dp"
        android:layout_marginTop="32dp"
        android:background="@drawable/rect"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow

            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/checkA_dateTitleText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="재고등록일"
                android:textSize="36sp" />

            <TextView
                android:id="@+id/checkA_nameTitleText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="품 명"
                android:textSize="36sp" />
        </TableRow>

    </TableLayout>

이제 이 코드를 넣어주면 아래처럼 한쪽으로 쏠리게 됩니다. 

View를 TableLayout에 맞게 해주려면 TableLayout에 android:stretchColumns="*" 를 추가합니다.

<TableLayout
        android:stretchColumns="*"
        android:layout_width="1187dp"
        android:layout_height="733dp"
        ...

    </TableLayout>

이제 새로운 Row를 추가하면 가장 사이즈가 큰 셀에 맞춰집니다.

이제 행 자바코드로 동적으로 추가해보겠습니다.

public class PriceCheckActivity extends AppCompatActivity {
    private TableLayout tableLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 화면을 landscape(가로) 화면으로 고정하고 싶은 경우

        setContentView(R.layout.activity_price_check);

        tableLayout = (TableLayout) findViewById(R.id.tablelayout);
        TableRow tableRow = new TableRow(this);     // tablerow 생성
        tableRow.setLayoutParams(new TableRow.LayoutParams(
        			ViewGroup.LayoutParams.MATCH_PARENT, 
                            	ViewGroup.LayoutParams.WRAP_CONTENT));

        for(int i = 0 ; i < 5 ; i++) {
            TextView textView = new TextView(this);
            textView.setText(String.valueOf(i));
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(36);
            tableRow.addView(textView);		// tableRow에 view 추가
        }
        tableLayout.addView(tableRow);		// tableLayout에 tableRow 추가
    }
}

728x90

+ Recent posts