首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android ListFragment 找不到 setListAdapter()?正確位置在 onActivityCreated()

     編輯:程式設計綜合問答

錯誤現象

繼承 ListFragment 並在 onCreate() 中直接呼叫 setListAdapter(),編譯報錯「Cannot resolve method」。

根本原因

ListFragment 的 setListAdapter() 依賴內部 ListView 已建立完成。ListView 在 Fragment 的 onCreateView() 才會被建立(或使用預設佈局),因此必須在 視圖建立後 才能設定 Adapter。

正確生命週期位置

public class CrimeListFragment extends ListFragment {
    private ArrayList mCrimes;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.crimes_title);
        mCrimes = CrimeLab.get(getActivity()).getCrimes();
        // ❌ 這裡呼叫 setListAdapter() 會失敗,ListView 尚未建立
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // ✅ 正確位置:Activity 的 onCreate() 完成,Fragment 視圖已建立
        ArrayAdapter adapter = new ArrayAdapter<>(
            getActivity(),
            android.R.layout.simple_list_item_1,
            mCrimes
        );
        setListAdapter(adapter);
    }
}

關鍵生命週期對照

方法視圖狀態可呼叫 setListAdapter
onCreate()未建立❌
onCreateView()建立中(返回 View)❌ (ListView 可能尚未 attach)
onViewCreated()已建立✅ (API 17+ 推薦)
onActivityCreated()已建立並附著✅ (傳統寫法、相容性最好)

現代寫法建議

ListFragment 已被標記為 Deprecated (API 28+)。新專案請直接使用 Fragment + RecyclerView + ViewBinding:

public class CrimeListFragment extends Fragment {
    private FragmentCrimeListBinding binding;
    private CrimeAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentCrimeListBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter = new CrimeAdapter(CrimeLab.get(requireContext()).getCrimes());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.recyclerView.setAdapter(adapter);
    }
}

若維護舊專案必須用 ListFragment,請務必在 onActivityCreated() 或 onViewCreated() 設定 Adapter,切勿在 onCreate()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved