Android 在片段中动态添加的textView提供空引用

Android 在片段中动态添加的textView提供空引用,android,view,Android,View,因此,本质上,我正在制作一个测验应用程序,在应用程序的末尾,我有一个方法可以显示用户的进度。本质上,我想为用户输入的每个错误答案添加文本视图,但它告诉我它们都是空的。代码如下: public void progFinish() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view = getActivity().getLayoutInflater().in

因此,本质上,我正在制作一个测验应用程序,在应用程序的末尾,我有一个方法可以显示用户的进度。本质上,我想为用户输入的每个错误答案添加文本视图,但它告诉我它们都是空的。代码如下:

public void progFinish() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);

        TextView title = (TextView) mView.findViewById(R.id.title_dialog);
        int total = wrongChars.size();
        LinearLayout linearLayout = (LinearLayout) mView.findViewById(R.id.prog_dialog);

        for(Map.Entry<String, Integer> entry : wrongChars.entrySet()) {
            Log.d("test", entry.getKey());
            TextView wrongChar = new TextView(getActivity());
            wrongChar.setText(entry.getKey() + " \t" + entry.getValue() + " ");
            wrongChar.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

            linearLayout.addView(wrongChar);
        }

        builder.setView(view);
        AlertDialog dialog = builder.create();
        dialog.show();

    }
在onViewCreated中初始化。它们为空是否有特殊原因?我想这是因为mView,但我不确定

这是返回错误的行:

linearLayout.addView(wrongChar);

Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference

编辑:重要的是要注意,静态在布局中的textview膨胀得很好(当用户没有发现任何错误时会显示出来),所以我认为可以安全地假设动态添加的textview是当前的问题。不确定原因。

结果表明,当您使用:

findViewById(R.id.name_of_view);
您将返回活动/片段布局内部的视图。在我的例子中,因为它是一个对话框,并且手头的布局与片段不同,所以它返回null,因为没有带有该ID的linearlayout

要修复它,我只需将其更改为:

        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.prog_dialog);
现在它正确地引用了正确的线性布局

        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.prog_dialog);