Android NewBie - 面向setAdapter ListView的问题

时间:2012-10-14 16:16:19

标签: android android-listview android-fragments

我是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);
    }
}

2 个答案:

答案 0 :(得分:3)

onCreate()之前调用

onCreateView()。 ListView还没有膨胀,这就是为什么你找不到它......

只需将当前onCreate()代码移至onCreateView()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;
}

来自Developer's Guide的图表:

Fragment Lifecycle

答案 1 :(得分:2)

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

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

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