Android में अलर्ट डायलॉग दिखाने का पूरा गाइड
यह ट्यूटोरियल आपको Android ऐप में अलर्ट डायलॉग बनाने और दिखाने का चरणबद्ध तरीका बताता है। अलर्ट डायलॉग उपयोगकर्ता से पुष्टि लेने या महत्वपूर्ण जानकारी दिखाने के लिए उपयोगी होते हैं।
चरण 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press The Back Button."
android:textStyle="bold"
android:textSize="24sp"
android:layout_centerInParent="true" />
</RelativeLayout>
चरण 3: MainActivity.java में कोड जोड़ें
src/MainActivity.java में निम्नलिखित कोड जोड़ें:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Do you want to exit?");
builder.setTitle("Alert!");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
चरण 4: AndroidManifest.xml में कोड जोड़ें
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>
ऐप चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें। Android Studio में प्रोजेक्ट की एक्टिविटी फ़ाइल खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और ऐप चलने पर डिफ़ॉल्ट स्क्रीन देखें।