एंड्रॉइड EditText में स्थायी इमेज/आइकन जोड़ना (XML द्वारा)
यह सरल ट्यूटोरियल दिखाता है कि XML एट्रिब्यूट का उपयोग करके EditText में स्थायी ड्रॉएबल इमेज कैसे जोड़ें - कोई Java कोड आवश्यक नहीं।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट (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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_marginTop="30dp"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingStart="5dp"
android:background="@drawable/rounded_edittext"
android:drawableStart="@android:drawable/ic_menu_search"
android:paddingLeft="5dp" />
</LinearLayout>
चरण 3: बैकग्राउंड (drawable/rounded_edittext.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke android:width="1dp" android:color="#2f6699" />
<corners android:radius="10dp" />
</shape>
XML एट्रिब्यूट समझें
| एट्रिब्यूट | स्थिति | उपयोग |
|---|---|---|
drawableStart | शुरुआत (LTR में बाएं) | लीडिंग आइकन (सर्च, यूजर) |
drawableEnd | अंत (LTR में दाएं) | ट्रेलिंग आइकन (क्लियर, ड्रॉपडाउन) |
drawableLeft | हमेशा बाएं | पुराना, RTL में समस्या |
drawableRight | हमेशा दाएं | पुराना, RTL में समस्या |
drawableTop | ऊपर | कम उपयोग |
drawableBottom | नीचे | कम उपयोग |
अतिरिक्त स्टाइलिंग
<EditText
...
android:drawableStart="@drawable/ic_search"
android:drawablePadding="12dp" <!-- टेक्स्ट-इमेज गैप -->
android:drawableTint="@color/primary" <!-- इमेज रंग (API 23+) -->
android:paddingStart="16dp"
android:paddingEnd="16dp" />
प्रोग्रामेटिक विकल्प (Java/Kotlin)
// Java
editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_search, 0, 0, 0);
// Kotlin
editText.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_search, 0, 0, 0)
// क्लिक लिस्टनर (केवल दाएं/एंड ड्रॉएबल के लिए)
editText.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
Drawable drawableEnd = editText.getCompoundDrawables()[2];
if (drawableEnd != null && event.getRawX() >= (editText.getRight() - drawableEnd.getBounds().width())) {
// क्लिक हुआ - क्लियर करें या एक्शन लें
editText.setText("");
return true;
}
}
return false;
});
ऐप चलाएं
डिवाइस पर चलाएं - सर्च आइकन के साथ गोल EditText तुरंत दिखेगा, कोई कोड आवश्यक नहीं।