Просмотры не найдены для Alert Dialog во фрагментах - PullRequest
1 голос
/ 28 октября 2019

Я пытаюсь заполнить диалоговое окно оповещения (с файлом макета, имеющим EditText & Button) внутри фрагмента из Activity. Компоненты не найдены путем вызова findViewById () в фрагменте , соответствующем классу . Я написал этот код внутри класса:

    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

Я думаю, что проблема возникает из этой строки кода:

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

Код XML alertDialog приведен ниже:

<?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>

Может кто-нибудь найти, в чем проблема? Спасибо!

Ответы [ 3 ]

1 голос
/ 28 октября 2019

Вы можете сделать это, как показано ниже.

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(); 
1 голос
/ 28 октября 2019

Да, это правильно
Сделайте что-то вроде этого:

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();
0 голосов
/ 28 октября 2019

Попробуйте использовать dialog.setContentView(v)

См. Разницу между setView(v) и setContentView(v) здесь: В чем разница между Dialog.setContentView (View) и AlertDialog.setView (View)

...