FindViewById Возвращает значение null внутри BottomSheetDialogFragment

Сейчас я работаю над BottomSheetDialogFragment. Итак, я хочу создать пользовательскую кнопку, чтобы закрыть диалоговое окно внутри себя, как это

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:orientation = "vertical"
    android:paddingLeft = "@dimen/level_12"
    android:paddingRight = "@dimen/level_12"
    android:paddingBottom = "@dimen/level_20">

    <RelativeLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:gravity = "end">

        <TextView
            android:id = "@+id/taste_filter_close_button"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:clickable = "true"
            android:focusable = "true"
            android:padding = "@dimen/level_10"
            android:text = "@string/bottom_close_button" />
    </RelativeLayout>

    <TextView
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "@string/basic_taste_filter_title"
        android:textColor = "@color/colorPrimaryDark"
        android:textSize = "18sp"
        android:textStyle = "bold" />

    <TextView
        android:id = "@+id/textView"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_marginBottom = "@dimen/level_10"
        android:text = "@string/basic_taste_filter_subtitle_default" />

    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:baselineAligned = "false"
        android:orientation = "horizontal"
        android:weightSum = "1">

        <FrameLayout
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "0.2"
            android:paddingStart = "@dimen/level_flat"
            android:paddingLeft = "@dimen/level_flat"
            android:paddingEnd = "@dimen/level_2"
            android:paddingRight = "@dimen/level_2">

            <Button
                style = "?android:attr/buttonBarButtonStyle"
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                android:background = "@color/green_filter_button_bg"
                android:drawableTop = "@drawable/ic_filter"
                android:paddingTop = "@dimen/level_8"
                android:paddingBottom = "@dimen/level_8"
                android:text = "@string/sweet"
                android:textColor = "@color/green_filter_button_text" />
        </FrameLayout>
    </LinearLayout>
</LinearLayout>

Затем я показываю нижний диалог, используя этот метод.

private void showFoodListFilterButton() {
        Button foodListFilterButton = (Button) getActivity().findViewById(R.id.food_filter_button);
            foodListFilterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tasteFilterBottomDialogFragment = TasteFilterBottomDialogFragment.newInstance();
                tasteFilterBottomDialogFragment.show(getActivity().getSupportFragmentManager(), "Taste");
                hideFoodListFilterButton();
            }
        });
    }

Поэтому после этого я пытаюсь отклонить его, вызывая dismiss() внутри себя вот так.

public class TasteFilterBottomDialogFragment extends BottomSheetDialogFragment {

    public static TasteFilterBottomDialogFragment newInstance() {
        return new TasteFilterBottomDialogFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bottom_filter_dialog, container, false);
        // get the views and attach the listener
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        TextView closeBtn = (TextView) getActivity().findViewById(R.id.taste_filter_close_button);
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }
}

Но когда я нажимаю на кнопку taste_filter_close_button, я получаю это error

'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Итак, как я могу это исправить, или я что-то упустил?

Спасибо!

0
0
1 166
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Поскольку эта кнопка надувается во время onCreateView, вы можете установить слушателя во время onCreateView():

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bottom_filter_dialog, container, false);

    // get the views and attach the listener

    TextView closeBtn = (TextView) view.findViewById(R.id.taste_filter_close_button);
    closeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    return view;
}

Обратите внимание, что я делаю view.findViewById(), а не getActivity().findViewById()

Другие вопросы по теме