android-fragments 将代码添加到片段Activity中时应用程序崩溃

yptwkmov  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(155)

我是android studio的新手,所以我想创建一个使用导航抽屉在3个不同片段之间切换的应用程序。我使用了android studio的预建导航抽屉,我想在其中一个片段中放入一些代码。但是,当我初始化TextView(或其他东西)时,当我试图打开片段时,应用程序立即崩溃。
下面是GalleryActivity中的代码:

public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    private TextView testTV;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);

        binding = FragmentGalleryBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textGallery;
        galleryViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initWidgets();

        testTV.setText("Hello");
    }

    public void initWidgets(){
       testTV = testTV.findViewById(R.id.text_gallery);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

图片库.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".ui.gallery.GalleryFragment">

    <TextView
        android:id="@+id/text_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

日志目录:

2022-06-07 03:32:20.006 12339-12339/com.example.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testapp, PID: 12339
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
        at com.example.testapp.ui.gallery.GalleryFragment.initWidgets(GalleryFragment.java:46)
        at com.example.testapp.ui.gallery.GalleryFragment.onViewCreated(GalleryFragment.java:40)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3019)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:551)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2022-06-07 03:32:20.040 12339-12339/com.example.testapp I/Process: Sending signal. PID: 12339 SIG: 9

有谁能告诉我我做错了什么吗?提前感谢!

vnzz0bqm

vnzz0bqm1#

你从来没有初始化过testTV,所以它是空的。然后你试图在这个命令中使用它来初始化它自己,这是永远不会起作用的。

testTV = testTV.findViewById(R.id.text_gallery); // testTV is null

如果你必须使用findViewById,你需要在根视图上调用它,你可以从onViewCreated传入(例如view.findViewById())。

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // no need to save testTV as a class member, it is already
    // saved in the binding
    binding.textGallery.setText("Hello");
}

binding类是一个自动生成的helper类,它已经在布局中的所有视图上调用了findViewById,并将它们保存为类成员(当你用MyBinding.inflate()调用创建它时,它会这样做)。当使用binding时,你几乎不需要使用findViewById,也不需要存储单独的视图。

相关问题