1

I am trying to populate an Alert Dialog (with a layout file having an EditText & Button) within a fragment of Activity. The components are not being found by calling findViewById() in the fragment's corresponding class. I have written this code inside the class :

    AlertDialog.Builder builder=new AlertDialog.Builder(context); 
    View v=getLayoutInflater().inflate(R.layout.layout_alert_dialog,null);
    final EditText txtAddNew=v.findViewById(R.id.txtAddNew);                //null
    final TextView txtErr = v.findViewById(R.id.txtErr);                    //null
    Button btnAdd=v.findViewById(R.id.btnAdd);                              //null

I think the problem raises from this line of code:

 View v=getLayoutInflater().inflate(R.layout.layout_alert_dialog,null);

The alertDialog XML code is below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/txtAddNew"
        android:hint="Category name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtErr"
    />
    <Button
        android:id="@+id/btnAdd"
        android:text="Add Category" />
</LinearLayout>

Can anyone find what the actual problem is? Thanks!

3 Answers3

1

Yes, that's correct
Do something like this :

LayoutInflater layout = LayoutInflater.from(this);
final View view = layout.inflate(R.layout.dialog_layout, null);
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setView(view);
dialog.show();
Amjad Alwareh
  • 2,926
  • 22
  • 27
1

You can do it like below.

AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());    
alertBuilder.setView(getLayoutInflater().inflate(R.layout.layout_alert_dialog,null));
AlertDialog alertDialog = alertBuilder.create();
EditText txtAddNew = alertDialog.findViewById(R.id.txtAddNew);
TextView txtErr = alertDialog.findViewById(R.id.txtErr);
Button btnAdd = alertDialog.findViewById(R.id.btnAdd);
alertDialog.show(); 
Anjana
  • 903
  • 1
  • 5
  • 13
0

Try using dialog.setContentView(v)

See the difference between setView(v) and setContentView(v) here: What is difference between Dialog.setContentView( View ) & AlertDialog.setView( View )

Sharone Lev
  • 791
  • 7
  • 15