Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Tạo đường kẻ nét đứt (dotted/dashed line) trong Android

Mục tiêu

Tạo đường kẻ nét đứt (dotted/dashed) bằng cách sử dụng drawable shape với stroke.

Các bước

Bước 1: Tạo project mới

Bước 2: Layout activity_main.xml

<LinearLayout xmlns:android="..."
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#33FFFF00">

    <TextView android:id="@+id/text" ... android:text="click to show toast at top" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/dotted"
        android:layerType="software" />
</LinearLayout>

ImageView hiển thị drawable dotted.xml, height=5dp tạo thành đường kẻ ngang.

Tạo file 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" />
    <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape>

Lưu ý quan trọng: File shape trên tạo đường liền (solid stroke), không phải nét đứt. Để tạo nét đứt thực sự, cần dùng <stroke android:dashWidth="10dp" android:dashGap="5dp" /> (API 18+).

Bước 3: MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text = findViewById(R.id.text);
        text.setText("Dotted line for text view");
    }
}

Kết quả

Màn hình hiển thị đường kẻ (theo code gốc là nét liền):

Tạo đường kẻ nét đứt (dotted/dashed line) trong Android

Cách tạo nét đứt thực sự (bổ sung)

<shape xmlns:android="..." android:shape="rectangle">
    <stroke
        android:width="2dp"
        android:color="#4fa5d5"
        android:dashWidth="10dp"
        android:dashGap="5dp" />
</shape>

Thuộc tính dashWidth và dashGap yêu cầu API 18 (Android 4.3) trở lên. Cần set android:layerType="software" cho View nếu test trên emulator/API thấp.