如何在android应用程序中解决未定义的getactivity?

时间:2014-09-08 22:49:30

标签: android list static

我有这段代码我想在静态列表中显示这个虚拟数据,但是我在扩展片段和get活动中得到错误,我该如何解决它们?我需要更改它的任何部分吗?

 public class AgendaFragment extends Fragment{

    private ArrayAdapter<String> magendaAdapter;

public AgendaFragment() {
}


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        String[] data = {
                "Monday  going to restaurant at 14",
                "Monday  going to restaurant at 1",
                "Monday  going to restaurant at 1",
        };
        List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));


        magendaAdapter =
                new ArrayAdapter<String>(
                        getActivity(), // The current context (this activity)
                        R.layout.list_item_agenda, // The name of the layout ID.
                        R.id.list_item_agenda_textview, // The ID of the textview to populate.
                        weekForecast);

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Get a reference to the ListView, and attach this adapter to it.
        ListView listView = (ListView) rootView.findViewById(R.id.listview_agenda);
        listView.setAdapter(magendaAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = magendaAdapter.getItem(position);
                Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show();
            }
        });

        return rootView;
    }
}

1 个答案:

答案 0 :(得分:0)

添加

import android.app.Fragment;

在代码文件的开头。

(如果您使用的是Android支持库,则为android.support.v4.app.Fragment