परिचय
एक कस्टम डायलॉग उपयोगकर्ता इनपुट लेने या कस्टम लेआउट के साथ जानकारी प्रदर्शित करने की अनुमति देता है। यह लेख `AlertDialog.Builder` और एक कस्टम XML लेआउट का उपयोग करके एक कस्टम डायलॉग बनाने का तरीका दिखाता है।
चरण-दर-चरण कार्यान्वयन
चरण 1: मुख्य लेआउट (activity_main.xml)
<Button
android:id="@+id/btn_show"
android:layout_width="140dp"
android:layout_height="80dp"
android:layout_centerInParent="true"
android:text="Show Message"
android:onClick="btn_showMessage" />चरण 2: कस्टम डायलॉग लेआउट (custom_dialog.xml)
रिसोर्स → लेआउट → नया → लेआउट रिसोर्स फाइल → नाम: `custom_dialog`, रूट: `LinearLayout`
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<TextView android:text="Enter your Message" android:textSize="22sp" android:gravity="center" ... />
<EditText android:id="@+id/txt_input" android:hint="Enter your Message" android:textSize="20sp" ... />
<LinearLayout android:orientation="horizontal" ...>
<Button android:id="@+id/btn_cancel" android:text="Cancel" android:layout_weight="1" ... />
<Button android:id="@+id/btn_okay" android:text="Okay" android:layout_weight="1" ... />
</LinearLayout>
</LinearLayout>चरण 3: MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView myCustomMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCustomMessage = findViewById(R.id.myCustommessage);
}
public void btn_showMessage(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText input = dialogView.findViewById(R.id.txt_input);
Button cancel = dialogView.findViewById(R.id.btn_cancel);
Button okay = dialogView.findViewById(R.id.btn_okay);
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
cancel.setOnClickListener(v -> dialog.dismiss());
okay.setOnClickListener(v -> {
myCustomMessage.setText(input.getText().toString());
dialog.dismiss();
});
dialog.show();
}
}व्याख्या
- `LayoutInflater` कस्टम XML को व्यू में फुलाता है।
- `AlertDialog.Builder.setView()` कस्टम व्यू सेट करता है।
- बटनों के क्लिक लिसनर डायलॉग को खारिज करते हैं या इनपुट को मुख्य टेक्स्टव्यू में सेट करते हैं।