I have an AlertDialog in my app that contains an EditText field. This dialog needs to be generated programmatically and should match the way the EditTextPreference dialog looks that is displayed automatically by Android when a user edits text by touching an EditTextPreference. This all works, but the size of the EditText inserted programmatically is too wide and doesn't match the one displayed by the EditTextPreference when touched. The following two images show the problem.
EditText looks like this when added to the AlertDialog using setView():
But should look like this:
Here is the XML code in the XML responsible for the EditTextPreference:
<EditTextPreference
android:title="Enter Name"
android:key="name"
android:defaultValue=""
android:summary=""
android:inputType="textCapSentences|textMultiLine"
android:singleLine="false"
android:gravity="top|left"
android:lines="2"
android:minLines="1"
android:maxLines="2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
/>
And the Java code responsible for my dialog:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
final EditText input = new EditText(mainActivity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
input.setGravity(android.view.Gravity.TOP|android.view.Gravity.LEFT);
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
input.setLines(1);
input.setMaxLines(1);
input.setText(lastDateValue);
alertDialog.setView(input);
You have to add a container before doing that, e.g LinearLayout
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainActivity);
alertDialog.setTitle("Enter Date");
LinearLayout container = new LinearLayout(this);
container.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
final EditText input = new EditText(mainActivity);
input.setLayoutParams(lp);
input.setGravity(android.view.Gravity.TOP|android.view.Gravity.LEFT);
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
input.setLines(1);
input.setMaxLines(1);
input.setText(lastDateValue);
container.addView(input, lp);
alertDialog.setView(container);
I hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With