1. Create layout for the dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10sp">
<EditText android:text=""
android:id="@+id/categoryEditText"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:singleLine="true">
</EditText>
</LinearLayout>
2. Override onCreateDialog in the Activity
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CATEGORY_DETAIL:
LayoutInflater li = LayoutInflater.from(this);
View categoryDetailView = li.inflate(R.layout.category_detail, null);
AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
categoryDetailBuilder.setTitle("Edit Category");
categoryDetailBuilder.setView(categoryDetailView);
AlertDialog categoryDetail = categoryDetailBuilder.create();
categoryDetail.setButton("OK", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
if (categories.get(selectedIndex)!=null){
//... some code
}
});
categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}});
return categoryDetail;
default:
break;
}
return null;
}
3. Override onPrepareDialog to dynamically set default value before the dialog is open
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case CATEGORY_DETAIL:
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
et.setText(defaultValue);
break;
default:
break;
}
}
static final private int CATEGORY_DETAIL = 1; //... some code showDialog(CATEGORY_DETAIL);