未显示简单ListView作为片段

时间:2016-01-30 14:24:08

标签: java android listview

我尝试将ListView添加到我的MainActivity中,但我不知道为什么它不会出现在App中。

我创建了一个名为“list_item_forecast.xml”的新布局资源文件 - 在那里我放置了一个带有id:“list_item_forecast_textview”的TextView。

在“content_main.xml”中我有ListView:

<ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview_forecast" />

然后我在MainActivity Class中有这个类:

 public static class PlaceholderFragment extends Fragment{
    ArrayAdapter<String> mForecastAdapter;
    public PlaceholderFragment(){

    }
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.content_main, container,false);

        String[] forecastArray = {
                "Heute - Sonnig - 34°",
                "Morgen - Sonnig - 30°",
                "Montag - Regen - 10°",
                "Dienstag - Bewölkt - 20°",
                "Mittwoch - Schnee - 10°",
                "Donnerstag - Schnee - 15°",
                "Freitag - Sonne - 33°"
        };
        List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
        mForecastAdapter = new ArrayAdapter<String>(getContext(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
        ListView listView = (ListView) rootView.findViewById(
                R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);
        return rootView;
    }

}

以下是整个项目: https://github.com/Zaniyar/sunshine/tree/master/app/src/main

2 个答案:

答案 0 :(得分:0)

你应该在第41行new之后将你的片段添加到活动中 你的主要活动,我的意思是 this file

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(x, "some_tag");

另请参阅此链接以获取更多信息

答案 1 :(得分:0)

我不得不改变&#34; getContext()&#34; to&#34; this.getActivity()&#34;在PlaceholderFragment.java中:

List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
    mForecastAdapter = new ArrayAdapter<String>(getContext(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
    ListView listView = (ListView) rootView.findViewById(
            R.id.listview_forecast);
    listView.setAdapter(mForecastAdapter);