Android में ImageView खाली करने का तरीका
यह उदाहरण दर्शाता है कि बटन क्लिक पर ImageView से इमेज कैसे हटाई जाती है। यह तब उपयोगी होता है जब आप उपयोगकर्ता की क्रिया पर इमेज को रीसेट करना चाहते हैं।
चरण 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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:onClick="ClickHere"
android:text="Click here" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_below="@id/imageView"
android:background="@drawable/wallpaper" />
</RelativeLayout>
चरण 3: MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
}
public void ClickHere(View view) {
imageView.setBackgroundDrawable(null);
}
}
चरण 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>
महत्वपूर्ण नोट
setBackgroundDrawable() विधि पुराने API लेवल के लिए है। नए Android वर्जन (API 16+) में setBackground(null) या setImageDrawable(null) का उपयोग करना बेहतर है। साथ ही, लेआउट में android:layout_below="@id/imageView" का उपयोग स्वयं उसी व्यू के लिए करना तार्किक रूप से गलत है; इसे ठीक करें।