Android custom dialog example
The following steps are for creating a basic custom dialog in Android by extending the Dialog class.
1. This is optional, but here is a drawable layout for making round corners for the custom dialog. dialog_shape.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#ffffff" /> <stroke android:width="2dp" android:color="#01FFFF" /> <corners android:radius="20dp"/> </shape>
2. Create the layout file for the custom dialog. custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/dialog_shape" android:orientation="vertical" > <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:text="Are you sure you want to quit?" android:textStyle="bold" android:gravity="center"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/tv_title" android:layout_margin="20dp" android:layout_gravity="center" android:gravity="center" android:orientation="horizontal" > <Button android:id="@+id/btn_no" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:clickable="true" android:text="No" android:textColor="#f25a55" android:textStyle="bold" /> <Button android:id="@+id/btn_yes" android:layout_width="100dp" android:layout_height="wrap_content" android:clickable="true" android:text="Yes" android:textColor="#35e664" android:textStyle="bold" /> </LinearLayout> </RelativeLayout>
3. Create the custom class which extends from the Dialog class for the custom dialog.
public class CustomDialog extends Dialog implements android.view.View.OnClickListener { public Activity activity; public Button btnYes, btnNo; public CustomDialog(Activity activity) { super(activity); this.activity = activity; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.custom_dialog); btnYes = (Button) findViewById(R.id.btn_yes); btnNo = (Button) findViewById(R.id.btn_no); btnYes.setOnClickListener(this); btnNo.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_yes: activity.finish(); break; case R.id.btn_no: dismiss(); break; default: break; } dismiss(); } }
4. Call the Custom Dialog.
CustomDialog customDialog = new CustomDialog(MainActivity.this); customDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); customDialog.show();
5. Modify the custom layout to whatever fits your need.
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts