2

我对 Android 完全陌生,第一次尝试使用 Fragments。我使用了我在片段中转换的 ListView 活动。但不知何故,由 findViewById() 检索到的 ListView 元素给了我 null。谁能帮我解决这个问题。?

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

 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);
    }
}
4

2 回答 2

3

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

只需将当前onCreate()代码移入onCreateView()or onActivityCreated()


onCreateView()通过保存对膨胀视图的引用,您应该能够轻松地设置您的 ListView :

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;
}

开发人员指南中的图表:

片段生命周期

于 2012-10-14T16:20:35.357 回答
2

您的问题是您试图在设置视图之前获取列表视图(onCreate之前调用过onCreateView)......您需要移动它

ListView timeTrackerListView = (ListView) getActivity().findViewById(R.id.time_tracker_List); 

以及任何引用该onCreateView方法的内容。

于 2012-10-14T16:23:09.207 回答