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

Cách tạo chữ chỉ số dưới (Subscript) và chỉ số trên (Superscript) trong Android

Giới thiệu

Ví dụ này minh họa cách định dạng văn bản với Subscript (chỉ số dưới, ví dụ: H₂O) và Superscript (chỉ số trên, ví dụ: x²) trong TextView sử dụng SpannableStringBuilder và các Span chuyên dụng.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="36sp"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed" />

</RelativeLayout>

Bước 3: Code MainActivity (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    String strText;
    SpannableStringBuilder spannableStringBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        strText = "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example.";
        spannableStringBuilder = new SpannableStringBuilder(strText);

        // Tạo các Span
        SubscriptSpan subscriptSpan = new SubscriptSpan();
        SuperscriptSpan superscriptSpan = new SuperscriptSpan();

        // Áp dụng Subscript cho ký tự '2' (vị trí của "X2")
        int index2 = strText.indexOf("2");
        spannableStringBuilder.setSpan(subscriptSpan, index2, index2 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // Áp dụng Superscript cho ký tự '5' (vị trí của "Y5")
        int index5 = strText.indexOf("5");
        spannableStringBuilder.setSpan(superscriptSpan, index5, index5 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // Thu nhỏ kích thước chữ cho các chỉ số (tùy chọn, để đẹp hơn)
        showSmallSizeText("2");
        showSmallSizeText("5");

        // Hiển thị
        textView.setText(spannableStringBuilder);
    }

    // Hàm helper thu nhỏ kích thước chữ tại vị trí ký tự s
    private void showSmallSizeText(String s) {
        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.5f); // 50% kích thước gốc
        int index = strText.indexOf(s);
        spannableStringBuilder.setSpan(relativeSizeSpan, index, index + s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

Bước 4: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. TextView sẽ hiển thị: "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example." với chữ chỉ số nhỏ hơn.

Cách tạo chữ chỉ số dưới (Subscript) và chỉ số trên (Superscript) trong Android

Giải thích các Span quan trọng

Span Class Chức năng Ví dụ
SubscriptSpan Hạ thấp văn bản xuống dưới đường cơ sở (baseline) H₂O, CO₂
SuperscriptSpan Nâng văn bản lên trên đường cơ sở x², m³, 1st
RelativeSizeSpan Thay đổi kích thước tương đối (0.5f = 50%) Làm nhỏ chỉ số

Các Span hữu ích khác

  • ForegroundColorSpan: Đổi màu chữ.
  • BackgroundColorSpan: Đổi màu nền chữ.
  • StyleSpan: Bold, Italic, Bold-Italic.
  • UnderlineSpan, StrikethroughSpan: Gạch chân, gạch ngang.
  • ClickableSpan: Làm một đoạn text có thể nhấn.
  • ImageSpan: Chèn hình ảnh vào giữa text.

Mẹo thực tế

Với chuỗi động (từ database, API), hãy dùng regex hoặc duyệt ký tự để tìm vị trí cần áp dụng Span thay vì indexOf() cứng.