Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้างเส้นประ/เส้นขีดใน Android

วิธีสร้างเส้นประ/เส้นขีดใน Android

ตัวอย่างนี้สาธิตวิธีการสร้างเส้นประ/เส้นขีดใน Android

ขั้นตอนที่ 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 มีพื้นหลังแบบเส้นประ ดังนั้นให้สร้าง dotted.xml ในโฟลเดอร์ drawable ดังนี้:

<?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>

ขั้นตอนที่ 3 - เพิ่มโค้ดใน 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 จริงกับคอมพิวเตอร์แล้ว เพื่อรันแอปจาก Android Studio ให้เปิดไฟล์กิจกรรมของโปรเจกต์หนึ่งและคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก และตรวจสอบอุปกรณ์ซึ่งจะแสดงหน้าจอเริ่มต้น

วิธีสร้างเส้นประ/เส้นขีดใน Android

ผลลัพธ์ด้านบนมีเส้นประ