कोड से LayoutParams के साथ मार्जिन सेट करना
यह उदाहरण दिखाता है कि LinearLayout.LayoutParams और setMargins() का उपयोग करके रनटाइम में व्यू के मार्जिन कैसे सेट करें।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" />
चरण 3: MainActivity.java
package app.tutorialspoint.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = findViewById(R.id.linearLayout);
// LayoutParams बनाएं: चौड़ाई MATCH_PARENT, ऊंचाई WRAP_CONTENT
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
// मार्जिन सेट करें: left, top, right, bottom (पिक्सेल में)
layoutParams.setMargins(30, 20, 30, 0);
// बटन बनाएं और लेआउट में जोड़ें
Button okButton = new Button(this);
okButton.setText("कुछ टेक्स्ट");
ll.addView(okButton, layoutParams);
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.sample">
<uses-permission android:name="android.permission.VIBRATE" />
<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>
महत्वपूर्ण नोट्स
- पेरेंट लेआउट टाइप के अनुसार LayoutParams चुनें: LinearLayout के बच्चों के लिए
LinearLayout.LayoutParams, RelativeLayout के लिएRelativeLayout.LayoutParams, आदि। setMargins()में मान **पिक्सेल** में होते हैं। DP के लिए:(int) (dp * density + 0.5f)।- मौजूदा व्यू के मार्जिन बदलने के लिए:
((ViewGroup.MarginLayoutParams) view.getLayoutParams()).setMargins(...)फिरview.requestLayout()। - API 17+ (JB MR1) पर RTL सपोर्ट के लिए
setMarginStart()/setMarginEnd()का उपयोग करें।
आउटपुट
बटन 30px लेफ्ट/राइट, 20px टॉप मार्जिन के साथ LinearLayout में जुड़ जाएगा।
