gpt4 book ai didi

Android NewBie - setAdapter ListView 面临的问题

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:53 25 4
gpt4 key购买 nike

我是 Android 的新手,第一次尝试 Fragments。我使用了一个正在 fragment 中转换的 ListView Activity 。但不知何故,由 findViewById() 检索到的 ListView 元素给了我 null。谁能帮我解决这个问题?

这是 ListView Fragment 的代码,我在调用 setAdapter 方法后遇到错误。日志值显示 timeTrackerListView 为空。我不知道为什么。!! :(

 package ray.kaushik.nasaapp;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class TimeTracker extends Fragment{
private Time_Tracker_Adapter timeTrackerAdapter;
private String TAG = "TimeTracker";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
timeTrackerAdapter = new Time_Tracker_Adapter();

}

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.time__tracker_layout, container, false);
}

public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
ListView timeTrackerListView = (ListView) getActivity().findViewById(R.id.time_tracker_List);
Log.i(TAG, "timeTrackerListView-->" + timeTrackerListView);
timeTrackerListView.setAdapter(timeTrackerAdapter);
}
}

最佳答案

onCreate()onCreateView() 之前被调用。 ListView 还没有膨胀,这就是为什么你找不到它的原因......

只需将当前的 onCreate() 代码移动到 onCreateView()onActivityCreated() 即可。


您应该能够在 onCreateView() 中设置您的 ListView,只需保存对膨胀 View 的引用即可:

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.time__tracker_layout, container, false);
ListView timeTrackerListView = (ListView) view.findViewById(R.id.time_tracker_List);
timeTrackerAdapter = new Time_Tracker_Adapter();
timeTrackerListView.setAdapter(timeTrackerAdapter);
return view;
}

图表来自 Developer's Guide :

Fragment Lifecycle

关于Android NewBie - setAdapter ListView 面临的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com