Android TextView में लाइन ब्रेक जोड़ने के तरीके
यह ट्यूटोरियल दिखाता है कि कैसे strings.xml में \n एस्केप सीक्वेंस या HTML <br> टैग का उपयोग करके TextView में बहु-लाइन टेक्स्ट प्रदर्शित किया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनकर नया प्रोजेक्ट बनाएं।
चरण 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="@string/Questions" />
</RelativeLayout>
चरण 3: MainActivity.java में कोड जोड़ें
src/MainActivity.java में:
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setTextColor(Color.RED);
}
}
चरण 4: strings.xml में लाइन ब्रेक के साथ स्ट्रिंग जोड़ें
res/values/strings.xml में:
<resources>
<string name="app_name">Sample</string>
<string name="Questions">
1. What is your Favourite food?\n
2. Which is your favourite sport?\n
3. Whats your bucket list?
</string>
</resources>
लाइन ब्रेक के विभिन्न तरीके
| तरीका | उदाहरण | कहां काम करता है |
|---|---|---|
\n (एस्केप सीक्वेंस) | "Line 1\nLine 2" | strings.xml, Java कोड, setText() |
<br> (HTML) | "Line 1<br>Line 2" | Html.fromHtml() के साथ |
System.lineSeparator() | "Line 1" + System.lineSeparator() + "Line 2" | Java कोड में प्लेटफॉर्म-स्वतंत्र |
HTML तरीके का उपयोग (Java कोड में)
textView.setText(Html.fromHtml("Line 1<br>Line 2<br>Line 3"));
चरण 5: 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>
ऐप चलाएं
डिवाइस कनेक्ट करें, Run आइकन पर क्लिक करें और TextView में तीन अलग-अलग लाइनों पर प्रश्न देखें।