Android에서 테두리가있는 테이블을 어떻게 만들 수 있습니까?


187

테이블 레이아웃을 사용하여 데이터를 테이블로 표시하지만 사용자 정의 열과 행이 테두리가있는 테이블을 원합니다. 제안?

답변:


198

이 문제에 대한 나의 해결책은 모든 셀의 배경 필드에 XML 드로어 블 리소스를 넣는 것입니다. 이러한 방식으로 모든 셀에 대해 원하는 테두리가있는 모양을 정의 할 수 있습니다. 유일한 불편은 극단적 인 셀의 경계가 다른 셀의 너비의 절반을 차지하지만 테이블이 전체 화면을 채우더라도 아무런 문제가 없다는 것입니다.

예 :

drawable / cell_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#000"/>
        <stroke android:width="1dp"  android:color="#ff9"/>
</shape>

layout / my_table.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">

    <TableRow
        android:id="@+id/tabla_cabecera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></TableRow>

    <TableLayout
        android:id="@+id/tabla_cuerpo"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>
    </TableLayout>


</LinearLayout>

편집 : 예

여기에 이미지 설명을 입력하십시오

Edit2 : 또 다른 예 (더 많은 요소 : 원 모서리, 그라디언트 ...) 여기에 이미지 설명을 입력하십시오

http://blog.intelligenia.com/2012/02/programacion-movil-en-android.html#more 에서 자세한 내용 으로이 문제를 설명했습니다 . 스페인어로되어 있지만 더 복잡한 테이블의 코드와 이미지가 있습니다.


6
내용을 볼 수 없습니다
ashok reddy

1
프로그래밍 방식으로 뷰의 배경을 어떻게 설정합니까? view.setBackground(?)
rasen58

1
이를 보려면, 방금 전화 tabla_cabecera 첫 번째 행을 삭제
ymerdrengene

1
이렇게하면 테두리가 최소 2px 두께로 표시되어 1px 너비 테두리만큼 좋지 않습니다.
AndroidDev

1
그렇습니다. 유일한 불편이라고 설명했지만 테이블이 전체 화면을 채우면 아래쪽과 왼쪽 테두리를 1px로 설정할 수 있으며 1px 테두리가있는 테이블이됩니다.
David Jesse

56

브래드에 동의해야합니다. 그것은 끔찍한 대답이었습니다. Android 설명서에는 TableLayout 컨테이너에 경계선이 표시되지 않으므로 Android 사이트로 보내면 조금 도움이되지 않습니다. droidnova에서 "더러운"솔루션을 찾을 수있었습니다. 여기에는 TableLayout의 배경색을 설정 한 다음 TableRow의 다른 배경색을 설정하고 행에 layout_margin을 추가하는 것이 포함됩니다. 나는이 솔루션을 좋아하지 않지만 행 테두리에는 효과가 있습니다. 각 "셀"항목을 구성하는 항목을 사용하여 동일한 작업을 수행 할 수 있지만 확인하지 않았습니다.

DroidNova와 유사한 예 :

<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
  <TableRow android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="1dp">
     ...
  </TableRow>
</TableLayout>

1
여기에서 의도적 인 오버 드로우 문제를주의하십시오. 테이블이 크면 UI에서 king 거리거나 끊길 수 있습니다.
Vicky Chijwani 2012

프로그래밍 방식으로 layout_margin을 TableRow객체 에 어떻게 설정할 수 있습니까?
James Wierzba

그냥 테이블과 행 주위에 개요를 추가하지만 열 사이에는 추가하지 않습니다
user924

41

경우 그냥 (예를 들어, 그냥 "총"행 위) 행 사이의 라인을 가지고하려고하는 다음 쉬운 해결책이 - 단지 배경 색상으로 TableRow를 추가하고 특정이 같은 layout_height :

<TableRow android:layout_height="1px" android:background="#BDBDBD">
   <TextView android:layout_span="2" android:layout_height="1px" 
             android:layout_width="fill_parent" android:text="">
   </TextView>
</TableRow>

android:layout_height="1px"테두리를 설정 하거나 두껍게 만드십시오. 나머지 테이블과 일치시키는 데 필요한만큼 빈 TextView 열을 채우거나 android:layout_span설명 된대로 하나만 사용하십시오 .

결과는 다음과 같습니다.

표 테두리 설명

더 복잡한 테두리를 추가하려는 경우 이미 게시 된 다른 답변이 더 적합합니다.


왜 대신 TextView사용할 수 View있습니까? 또한 정확한 픽셀을 지정하는 것은 좋지 않습니다. 대신 dp / sp를 사용하십시오. 이 스레드를 참조하십시오 : stackoverflow.com/questions/2025282/...를 .
Stephan

피드백 주셔서 감사합니다 ... TextView를 사용할 이유가 없다고 생각합니다-그것은 단지 예일뿐입니다. 둘째, dp / sp를 오해하지 않는 한 (정확하게는 실제로 Android에서 약 일주일 동안 개발했기 때문에 px를 사용합니다) 행간에 1 픽셀 라인 만 보장하기 때문에 px를 사용합니다. 사용중인 해상도 또는 화면 크기. 나는 매우 얇은 선을 좋아합니다. 다른 사용자는 다른 취향을 가지고 다른 장치를 사용할 수 있습니다.
마이클 브레이

네,하지만 당신은 매우 얇은 라인을 좋아합니까! - 좋은 간단한 솔루션은 내 투표 얻는다 말했다
gheese

26

내가 원하는 것은 이런 테이블입니다

수직 분배기가있는 테이블 이미지

나는 이것을 styles.xml에 추가했다 :

      <style name="Divider">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@color/divider_color</item>
    </style>

    <style name="Divider_invisible">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
    </style>

그런 다음 내 테이블 레이아웃에서 :

 <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:stretchColumns="*" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:background="#92C94A" >

                <TextView
                    android:id="@+id/textView11"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider_invisible" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView12"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/main_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView13"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/side_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView14"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/total"
                    android:textColor="@color/white"
                    android:textSize="16sp" />
            </TableRow>

            <!-- display this button in 3rd column via layout_column(zero based) -->

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#6F9C33" >

                <TextView
                    android:id="@+id/textView21"
                    android:padding="5dp"
                    android:text="@string/servings"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

..........
.......
......

22

xml을 통하지 않고 비단 법적으로이 작업을 수행 할 수도 있지만 조금 더 "해킹"적입니다. 그러나 남자에게 옵션을 제공하지 않으면 선택의 여지가 없습니다. p .. 코드는 다음과 같습니다.

TableLayout table = new TableLayout(this);
TableRow tr = new TableRow(this);
tr.setBackgroundColor(Color.BLACK);
tr.setPadding(0, 0, 0, 2); //Border between rows

TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 0, 2, 0);//2px right-margin

//New Cell
LinearLayout cell = new LinearLayout(this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(llp);//2px border on the right for the cell


TextView tv = new TextView(this);
tv.setText("Some Text");
tv.setPadding(0, 0, 4, 3);

cell.addView(tv);
tr.addView(cell);
//add as many cells you want to a row, using the same approach

table.addView(tr);

14

자바 코드를 작성하지 않고 <shape...>태그를 사용 하여 다른 XML 레이아웃을 만들지 않고 모든 셀 주위에서 1dp 축소 경계를 만들려면 다음 해결책을 시도하십시오.

에서 <TableLayout...>추가 android:background="#CCC"android:paddingTop="1dp"android:stretchColumns="0"

에서 <TableRow...>추가 android:background="#CCC"android:paddingBottom="1dp"android:paddingRight="1dp"

TableRow에서 모든 세포 / 아이에서, 즉 <TextView...>추가 android:background="#FFF"하고android:layout_marginLeft="1dp"

설명 된대로 패딩과 여백을 따르는 것이 매우 중요합니다. 이 솔루션은 (X) HTML / CSS에서 1dp 테두리 일명 border-collapse 속성을 그립니다.

백그라운드 컬러 <TableLayout...><TableRow...>의 경계선 색상 및 배경 나타내는 <TextView...>필 테이블 셀. 필요한 경우 일부 패딩을 셀에 넣을 수 있습니다.

예를 들면 다음과 같습니다.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#CCC"
    android:paddingTop="1dp"
    android:stretchColumns="0"
    android:id="@+id/tlTable01">

    <TableRow
        android:background="#CCC"
        android:paddingBottom="1dp"
        android:paddingRight="1dp">
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:text="Item1"/>
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:gravity="right"
            android:text="123456"/>
    </TableRow>
    <TableRow
        android:background="#CCC"
        android:paddingBottom="1dp"
        android:paddingRight="1dp">
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:text="Item2"/>
        <TextView 
            android:layout_marginLeft="1dp"
            android:padding="5dp"
            android:background="#FFF"
            android:gravity="right"
            android:text="456789"/>
    </TableRow>
</TableLayout>

환상적인! 감사!
superodde

이것은 좋지만 어두운 모드를 사용하려고 할 때 문제가 있습니다. 흰색 테두리를 가지려면 TableRow background = white에 넣어야하기 때문입니다. 이제 두 번째 TextView가 첫 번째 TextView보다 길어질 때 첫 번째 TextView 뒤에 흰색 배경이 나타납니다. 첫 번째 TextView의 배경을 어둡게 설정하면 전체보기를 다루지 않으므로 도움이되지 않습니다.
Wiktor Kalinowski

1
이것은 내가 찾던 것입니다 ... 감사합니다 @WiktorKalinowski가 말한 것은 우리가 수동으로 놀아야하는 어두운 모드에도 해당됩니다.
Hi Ten

14

여기에 이미지 설명을 입력하십시오

여기에 다음 디자인 이미지로 목록을 디자인했습니다. 내 listitem 파일 이름은 Propertylistitem.xml 이고 cellborder.xml 은 cellborder 출력을 위해 drawable 모양으로 사용 되며이 이미지에 표시됩니다. 필요한 코드는 여기에 추가했습니다.

파일 이름 : propertylistitem.xml

<TableLayout... >
            <TableRow... >
                 <TextView ...
                    android:background="@drawable/cellborder"
                    android:text="Amount"/>
            </TableRow>

            <TableRow... >
                <TextView...
                    android:background="@drawable/cellborder"
                    android:text="5000"/>
            </TableRow>
        </TableLayout>

filename : cellborder.xml 여기서는 단지 디자인에 테두리 만 원하므로 단색 태그를 주석으로 넣습니다.

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <!--     <solid android:color="#dc6888"/>     -->
        <stroke android:width="0.1dp" android:color="#ffffff"
            />
        <padding android:left="0dp" android:top="0dp"
                android:right="0dp" android:bottom="0dp" />
    </shape>

8

긴 검색과 몇 시간 동안 시도한 후에는 내가 만들 수있는 가장 간단한 코드입니다.

ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Style.STROKE);
border.getPaint().setColor(Color.BLACK);
tv.setBackground(border);
content.addView(tv);

tv는 간단한 텍스트가있는 TextView이고 내용은 내 컨테이너입니다 (이 경우 LinearLayout). 조금 더 쉽습니다.


API의 LVL (16) :( 필요
AndacAydin

setBackgroundDrawable()대신 사용할 수 있습니다.
Corey Wu

8

글쎄요, 그 단계는 경계 테이블을 동적으로 만드는 방법을 보여 줍니다.

여기 테이블 뷰입니다

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nested_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    android:scrollingCache="true">
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/simpleTableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="45dp"
        android:layout_marginRight="45dp"
        android:stretchColumns="*"
        >
    </TableLayout>
</android.support.v4.widget.NestedScrollView>

여기 "attrib_row.xml" 을 사용하는 행

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/border"
    >
    <TextView
        android:id="@+id/attrib_name"
        android:textStyle="bold"
        android:height="30dp"
        android:background="@drawable/border"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/attrib_value"
        android:gravity="center"
        android:height="30dp"
        android:textStyle="bold"
        android:background="@drawable/border"
        />
</TableRow>

"border.xml" 테이블에 테두리를 추가하기 위해이 XML 파일을 드로어 블에 추가 할 수 있습니다

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle">
    <solid android:color="@color/colorAccent"/>
    <stroke android:width="1dp" android:color="#000000"/>
</shape>

마지막으로 Kotlin으로 작성된 컴팩트 코드가 있지만 필요한 경우 Java로 쉽게 변환 할 수 있습니다.

well temps는 배열 목록에 데이터가 포함되어 있습니다. ArrayList<Double>()

fun CreateTable()
{
    val temps=controller?.getTemps()
    val rowHead = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
    (rowHead.findViewById<View>(R.id.attrib_name) as TextView).text=("time")
    (rowHead.findViewById<View>(R.id.attrib_value) as TextView).text=("Value")
    table!!.addView(rowHead)
    for (i in 0 until temps!!.size) {

        val row = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
        (row.findViewById<View>(R.id.attrib_name) as TextView).text=((i+1).toString())
        (row.findViewById<View>(R.id.attrib_value) as TextView).text=(temps[i].toString())
        table!!.addView(row)
    }
    table!!.requestLayout()
}

예를 들어 다음과 같이 조각 에 사용할 수 있습니다.

   override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        table = view?.findViewById<View>(R.id.simpleTableLayout) as TableLayout
        CreateTable()
    }

최종 결과는 다음과 같습니다 여기에 이미지 설명을 입력하십시오


5

onDraw 메서드를 재정의 한 다음 캔버스에 선을 그리는 것은 어떻습니까?

for(int i = 0; i < rows; i++)
    {
        canvas.drawLine(0, i * m_cellHeight, m_totalWidth, i * m_cellHeight, paint);
    }
    for(int i = 0; i < m_columns; i++){
        canvas.drawLine(i* m_cellWidth, 0, i * m_cellWidth, m_cellHeight * rows, paint);
    }

3

이 솔루션을 사용했습니다 :에서 수직선과 실제 셀이있는 TableRow모든 셀에 대해 생성하고 매번 수평선을 추가했습니다.LinearLayoutTableRow

아래 코드를보십시오 :

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

그것이 도움이되기를 바랍니다.


이것은 행 아래에 한 줄을 추가하는 간단한 방법입니다.
Mark.ewd

3

이 문제를 해결하는 좋은 방법은 다음과 같습니다.

다음과 같이 모서리가 둥근 직사각형 드로어 블을 만듭니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <stroke android:width="2dp"
            android:color="#888888"/> 

    <corners android:bottomRightRadius="6dp" 
             android:bottomLeftRadius="6dp" 
             android:topLeftRadius="6dp" 
             android:topRightRadius="6dp"/> 
</shape>

이름을 rounded_border.xml로 drawable 폴더에 저장하십시오.

그런 다음 rounded_border를 다음과 같은 배경으로 사용하는 상대 레이아웃을 만듭니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@drawable/rounded_border">
   <ListView 
       android:id="@+id/list_view"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"/>

</RelativeLayout>

레이아웃 폴더에 저장하고 이름을 table_with_border.xml로 지정하십시오.

그런 다음 그러한 테이블이 필요할 때마다 다음과 같은 include 구문을 사용하여 뷰로 가져옵니다.

<include
        android:id="@+id/rounded_table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/table_with_border" />

가장자리 주위에 약간의 간격을 추가하고 싶을 수도 있습니다. LinearLayout에 포함을 감싸고 가장자리 주위에 패딩을 추가하십시오.

테이블 주위에 예쁜 테두리를 만드는 간단하고 쉬운 방법.


2

미드 델 섹션에서 스트로크가 두 배로 증가했습니다.이 레이어 목록 드로어 블을 사용했습니다.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">

     <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
       <solid android:color="@color/grey" />
    </shape>
</item>

<item android:top="1dp" android:left="1dp" android:bottom="1dp" android:right="1dp">

    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
      <solid android:color="@color/lightgrey" />
    </shape>
 </item>
</layer-list>

2

1px 9 패치 이미지를 만드는 것이 가장 좋으며, TableRow 및 TableLayout에서 showDividers 특성을 사용하는 것이 모두 LinearLayouts이므로


간단한 예를 들어 줄 수 있습니까?
Hossein Shahdoost

2

위의 답변에서 셀 사이의 경계가 두 배가됩니다. 따라서이 솔루션을 시도해 볼 수 있습니다.

<item
    android:left="-1dp"
    android:top="-1dp">

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
           android:shape="rectangle">
        <solid android:color="#fff"/>
        <stroke
            android:width="1dp"
            android:color="#ccc"/>
    </shape>
</item>


2

또 다른 해결책은 선형 레이아웃을 사용하고 다음과 같이 행과 셀 사이에 구분선을 설정하는 것입니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        ></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        ></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></LinearLayout>
    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>
</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>
</LinearLayout>

더러운 솔루션이지만 간단하고 투명한 배경 및 테두리와 함께 작동합니다.


2

나는 이것이 오래된 질문이라는 것을 알고있다.

다음은 가로 및 세로 막대뿐만 아니라 테이블보기 주위에 사각형을 그리는 빠르고 더러운 구현입니다.

public class TableLayoutEx extends TableLayout {
    private Paint linePaint = null;
    private Rect tableLayoutRect;

    public TableLayoutEx(Context context) {
        super(context);
    }

    public TableLayoutEx(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        float strokeWidth = this.getContext().getResources().getDisplayMetrics().scaledDensity * 1;
        linePaint = new Paint(0);
        linePaint.setColor(0xff555555);
        linePaint.setStrokeWidth(strokeWidth);
        linePaint.setStyle(Paint.Style.STROKE);

        Rect rect = new Rect();           
        int paddingTop= getPaddingTop();

        this.getDrawingRect(rect);
        tableLayoutRect = new Rect(rect.left, rect.top + paddingTop, rect.right, rect.bottom);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        Rect rect = new Rect();

        if (linePaint != null) {
            canvas.drawRect(tableLayoutRect, linePaint);
            float y = tableLayoutRect.top;
            for (int i = 0; i < getChildCount() - 1; i++) {
                if (getChildAt(i) instanceof TableRow) {
                    TableRow tableRow = (TableRow) getChildAt(i);
                    tableRow.getDrawingRect(rect);
                    y += rect.height();
                    canvas.drawLine(tableLayoutRect.left, y, tableLayoutRect.right, y, linePaint);
                    float x = tableLayoutRect.left;
                    for (int j = 0; j < tableRow.getChildCount() - 1; j++) {
                        View view = tableRow.getChildAt(j);
                        if (view != null) {
                            view.getDrawingRect(rect);
                            x += rect.width();
                            canvas.drawLine(x, tableLayoutRect.top, x, tableLayoutRect.bottom, linePaint);
                        }
                    }
                }
            }
        }
    }
}

세 번째 열 줄 바꿈 텍스트가있는 xml 예제 :

<com.YOURPACKAGE.TableLayoutEx
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="2"
    android:paddingTop="6dp">

    <TableRow>
        <TextView
            android:text="@string/my_text_0_0"
            android:padding="@dimen/my_padding"/>
        <TextView
            android:text="@string/my_text_0_1"
            android:padding="@dimen/my_padding"/>
        <TextView                   
            android:text="@string/my_text_0_2_to_wrap"
            android:padding="@dimen/my_padding"/>
    </TableRow>

    <!--more table rows here-->

</com.YOURPACKAGE.TableLayoutEx>

2

테두리가있는 테이블이 필요한 경우 TableLayout 대신 가중치가있는 선형 레이아웃을 제안합니다.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:gravity="center"
    android:padding="7dp"
    android:background="@drawable/border"
    android:textColor="@android:color/white"
    android:text="PRODUCT"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@android:color/black"
    android:paddingStart="1dp"
    android:paddingEnd="1dp"
    android:paddingBottom="1dp"
    android:baselineAligned="false">

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp">

        <TextView
            android:id="@+id/chainprod"
            android:textSize="15sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/pdct"/>

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:id="@+id/chainthick"
            android:textSize="15sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/thcns"/>

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:id="@+id/chainsize"
            android:textSize="15sp"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/size" />
    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:textSize="15sp"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/sqft" />
    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@android:color/black"
    android:paddingStart="1dp"
    android:paddingEnd="1dp"
    android:paddingBottom="1dp"
    android:baselineAligned="false">

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp">

        <TextView
            android:id="@+id/viewchainprod"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/pdct" />

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:id="@+id/viewchainthick"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/thcns"/>
    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:id="@+id/viewchainsize"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/size"/>
    </LinearLayout>
    <LinearLayout
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:layout_marginStart="1dp">

        <TextView
            android:id="@+id/viewchainsqft"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:background="@android:color/white"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:text="@string/sqft"/>

    </LinearLayout>
</LinearLayout>

여기에 이미지 설명을 입력하십시오

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.