如何在 OnActivityCreated 中解决这个不受欢迎的问题?

Posted

技术标签:

【中文标题】如何在 OnActivityCreated 中解决这个不受欢迎的问题?【英文标题】:How to resolve this deprected problem in OnActivityCreated? 【发布时间】:2021-09-30 14:57:57 【问题描述】:

我得到 'onActivityCreated(android.os.bundle)' 已被弃用。

package example.com.fragmentrecycler;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple @link Fragment subclass.
 */
public class ListFrag extends Fragment 
    RecyclerView recyclerView;
    RecyclerView.Adapter myAdapter;
    RecyclerView.LayoutManager layoutManager;
    View view;

    public ListFrag() 
        // Required empty public constructor
    


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_list, container, false);
        return view;
    

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

        
    

    public void notifyDataChanged()
    
        myAdapter.notifyDataSetChanged();
    


这是我收到此错误的 java 文件。此代码是完整项目的一部分。我的代码没有出错。

【问题讨论】:

【参考方案1】:

onActivityCreated() 在 API 级别 28 中已弃用。

没有显示错误,因为不存在错误。不推荐使用意味着存在更新或更好的方法来处理内容。所以你需要将onActivityCreated() 更改为onCreate()。但正如我所见,如果您已经拥有FragmentonCreateView(),则无需再次调用它。保持您的项目清晰,并创建一个新的.java 文件。不要将所有内容都编码在一个文件中。

onCreate() 代表Activity onCreateView() 代表 Fragment

【讨论】:

以上是关于如何在 OnActivityCreated 中解决这个不受欢迎的问题?的主要内容,如果未能解决你的问题,请参考以下文章

Android 片段 onCreateView 与 onActivityCreated

为啥我们可以在 onActivityCreated 之前运行的 onCreateView 中调用 getActivity()?

对onActivityCreated片段回调有啥误解吗?

Fragment中onCreate()、onCreateView()和onActivityCreated()的区别和使用

在 onActivityCreated/onStart/onViewCreated 方法内的 getView() 上出现 NullPointerException 警告

在 onActivityCreated() 之后再次调用 Fragment 的 onAttach()