3

I tried to add a ListView to my MainActivity, but I don't know why it doesnt appear in the App.

I created a new Layout resource file named "list_item_forecast.xml" - there I placed a TextView with the id: "list_item_forecast_textview".

In "content_main.xml" I have the ListView:

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

And then I have this Class in my 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;
    }

}

Here is the whole project: https://github.com/Zaniyar/sunshine/tree/master/app/src/main

Suisse
  • 3,467
  • 5
  • 36
  • 59

2 Answers2

0

you should add your fragment to activity after you new it in line 41 of your main activity ,i mean this file

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

also see this links for more information

Community
  • 1
  • 1
Rahmat Waisi
  • 1,293
  • 1
  • 15
  • 36
0

I had to change "getContext()" to "this.getActivity()" in 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);
Suisse
  • 3,467
  • 5
  • 36
  • 59