बटन क्लिक पर बैकग्राउंड कलर बदलना
यह सरल उदाहरण दिखाता है कि setOnClickListener और setBackgroundColor() का उपयोग करके बटन दबाने पर उसका बैकग्राउंड कलर कैसे बदलें।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="रंग बदलने के लिए क्लिक करें!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
चरण 3: MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
// colors.xml में परिभाषित कलर का उपयोग
button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
});
}
}
चरण 4: colors.xml में कलर जोड़ें (res/values/colors.xml)
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>
</resources>
चरण 5: 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>
बेहतर विकल्प: स्टेट लिस्ट ड्रॉएबल (सेलेक्टर)
XML में res/drawable/button_selector.xml बनाएं:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/colorPrimaryDark" />
<item android:state_focused="true" android:color="@color/colorAccent" />
<item android:color="@color/colorPrimary" />
</selector>
फिर लेआउट में: android:background="@drawable/button_selector"
आउटपुट
बटन क्लिक करने पर उसका बैकग्राउंड कलर प्राइमरी कलर में बदल जाएगा।

