Android में व्यू का बैकग्राउंड ड्रॉएबल प्रोग्रामेटिकली सेट करने का गाइड
यह ट्यूटोरियल दिखाता है कि कैसे setBackgroundResource() का उपयोग करके किसी भी व्यू (यहां RelativeLayout) का बैकग्राउंड इमेज/ड्रॉएबल रनटाइम पर बदला जाए।
चरण 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"
android:id="@+id/rl"
tools:context=".MainActivity">
<Button
android:text="Set Drawable"
android:id="@+id/btnSetDrawable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
</RelativeLayout>
चरण 3: MainActivity.java में कोड जोड़ें
src/MainActivity.java में:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.rl);
button = findViewById(R.id.btnSetDrawable);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
relativeLayout.setBackgroundResource(R.drawable.image);
}
});
}
}
तैयारी
अपने प्रोजेक्ट के res/drawable/ फोल्डर में image.jpg या image.png नाम से एक इमेज फ़ाइल रखें (या कोड में R.drawable.image को अपने ड्रॉएबल संसाधन के नाम से बदलें)।
अन्य उपयोगी विधियां
setBackgroundDrawable(Drawable)- API 16 में डिप्रिकेटेड,setBackground(Drawable)उपयोग करेंsetBackgroundColor(int color)- सॉलिड कलर के लिएContextCompat.getDrawable(context, R.drawable.image)- ड्रॉएबल ऑब्जेक्ट प्राप्त करने के लिए
चरण 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>
ऐप चलाएं
डिवाइस कनेक्ट करें, Run आइकन पर क्लिक करें, "Set Drawable" बटन दबाएं और बैकग्राउंड इमेज बदलते देखें।