이 튜토리얼에서는 안드로이드(Android) 앱에서 점선 또는 파선(dashed line)을 만드는 방법을 단계별로 알아봅니다. 별도의 이미지 파일 없이 XML 드로어블(drawable)만으로 간단하게 구현할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:background="#33FFFF00"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:textAlignment="center"
android:text="click to show toast at top"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="5dp"
android:src="@drawable/dotted"
android:layerType="software" />
</LinearLayout>위 코드는 TextView와 ImageView로 구성되어 있습니다. 여기서 핵심은 ImageView인데, android:src="@drawable/dotted" 속성으로 점선 배경을 지정했습니다. 또한 android:layerType="software" 속성을 반드시 추가해야 하는데, 하드웨어 가속 환경에서는 파선(stroke의 dash) 렌더링이 제대로 표시되지 않을 수 있기 때문입니다.
dotted.xml 드로어블 생성
res/drawable 폴더에 dotted.xml 파일을 생성하고 아래와 같이 작성합니다.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<stroke
android:width="1dip"
android:color="#4fa5d5"
android:dashWidth="10dp"
android:dashGap="6dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape><stroke> 요소가 선의 두께와 색상을 담당합니다. 실제로 끊긴 파선을 표현하려면 android:dashWidth(대시 하나의 길이)와 android:dashGap(대시 사이 간격) 속성을 함께 지정하면 됩니다. 이 값을 조절해 점선의 밀도를 자유롭게 변경할 수 있습니다.
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView text;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
text = findViewById(R.id.text);
text.setText("Dotted line for text view");
}
}앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 목록에서 연결된 모바일 기기를 선택하면 기기 화면에 아래와 같은 결과가 표시됩니다.

위 결과에서 확인할 수 있듯이, ImageView 영역에 파란색 파선이 정상적으로 출력됩니다. 이처럼 shape 드로어블의 stroke 속성만 활용하면 구분선, 카드 테두리, 차트 등 다양한 UI 요소에 점선과 파선을 손쉽게 적용할 수 있습니다.