Custom alert dialog, Android

In this tutorial is shown how to create a custom dialog in Android.

See following steps :

  1. Put code snipset to your code.
  2. Create xml custom layout

1. Put following part to a code where you want call custom dialog:

LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.activity); View view = layoutInflater.inflate(R.layout.dialog, null); final AlertDialog alertD = new AlertDialog.Builder(MainActivity.activity, R.style.myDialog).create(); //Put margin around edittext

FrameLayout container = new FrameLayout(MainActivity.activity); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(10, 0, 10, 0);

 

final EditText input = new EditText(getContext()); input.setLayoutParams(params);

container.addView(input); builder.setView(container);

Button bt = (Button) view.findViewById(R.id.start); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertD.dismiss(); } }); alertD.setView(view); alertD.show();

 

 

 

2. And create  custom dialog xml, e.g. res/layout/custom_dialog.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp"> <TextView android:id="@+id/start" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@android:style/TextAppearance.Medium" android:text="@string/start"/> </LinearLayout>