SpannableStringBuilder और Span क्लासेज का उपयोग करके टेक्स्ट में सबस्क्रिप्ट (नीचे) और सुपरस्क्रिप्ट (ऊपर) लागू करने का तरीका।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट
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>
चरण 3: स्पैन लॉजिक
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);
// सबस्क्रिप्ट: X2 का '2'
SubscriptSpan subscriptSpan = new SubscriptSpan();
int index2 = strText.indexOf("2");
spannableStringBuilder.setSpan(subscriptSpan, index2, index2 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// सुपरस्क्रिप्ट: Y5 का '5'
SuperscriptSpan superscriptSpan = new SuperscriptSpan();
int index5 = strText.indexOf("5");
spannableStringBuilder.setSpan(superscriptSpan, index5, index5 + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// छोटा आकार दोनों के लिए
showSmallSizeText("2");
showSmallSizeText("5");
textView.setText(spannableStringBuilder);
}
private void showSmallSizeText(String s) {
RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.5f); // आधा आकार
int index = strText.indexOf(s);
spannableStringBuilder.setSpan(relativeSizeSpan, index, index + s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
मुख्य स्पैन क्लासेज
| क्लास | उपयोग |
|---|---|
SubscriptSpan | टेक्स्ट को बेसलाइन से नीचे करता है |
SuperscriptSpan | टेक्स्ट को बेसलाइन से ऊपर करता है |
RelativeSizeSpan | सापेक्ष आकार बदलता है (0.5f = 50%) |
ForegroundColorSpan | रंग बदलता है |
StyleSpan | बोल्ड, इटैलिक आदि |
उपयोग के मामले
- रासायनिक सूत्र: H2O, CO2
- गणितीय व्यंजक: x2, E=mc2
- फुटनोट संदर्भ