I have a code which inflates a custom layout inside an Alert Dialog. The Custom Layout consists of an EditText and a Button. What is the correct way to display the EditText String inside a Toast by clicking the Button ?
I have tried the below code but it doesn't seem to work.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Fetch", (dialog, which) -> {
}).setNeutralButton("Cancel", (dialog, which) -> {
});
final AlertDialog dialog = builder.create();
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.custom_layout, null);
dialog.setView(dialogLayout);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.show();
dialog.setOnShowListener(d -> {
EditText dialogNameEditText = dialog.findViewById(R.id.dialog_name_edittext);
Button dialogPrintButton = dialog.findViewById(R.id.dialog_print_button);
dialogPrintButton.setOnClickListener(v1 -> {
Toast.makeText(
TestActivity.this,
dialogNameEditText.getText().toString(),
Toast.LENGTH_SHORT
).show();
});
});
custom_layout.xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/dialog_name_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorDark"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:padding="10dp"
android:textColor="@color/colorWhite"
android:textColorHint="@color/colorLight" />
<Button
android:id="@+id/dialog_print_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimary"
android:text="Print"
android:textColor="@color/colorLight" />
</LinearLayout>