यह उदाहरण दर्शाता है कि Android TextView में android:gravity एट्रिब्यूट का उपयोग करके टेक्स्ट को क्षैतिज (हॉरिजॉन्टल) और लंबवत (वर्टिकल) केंद्र में कैसे संरेखित किया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट XML में gravity सेट करें
res/layout/activity_main.xml - दो TextViews अलग-अलग ग्रेविटी के साथ:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Text in Center Vertical" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:text="Text in Center Horizontal" />
</RelativeLayout>
ग्रेविटी विकल्प:
center- दोनों दिशाओं में केंद्रcenter_horizontal- केवल क्षैतिज केंद्रcenter_vertical- केवल लंबवत केंद्रstart,end,left,right,top,bottom- अन्य संरेखण
चरण 3: MainActivity.java
src/MainActivity.java - कोई अतिरिक्त कोड नहीं:
package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
चरण 4: 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>
ऐप चलाएं
पहला TextView लंबवत केंद्र में, दूसरा क्षैतिज केंद्र में दिखेगा।
