2016-01-30 25 views
3

我試圖添加一個ListView到我的MainActivity,但我不知道它爲什麼不出現在應用程序中。簡單的ListView作爲片段不會出現

我創建了一個名爲「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類別:

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

+0

您可以添加將代碼片段添加到活動的代碼嗎? –

+0

eeehm你如何做到這一點? 這是整個代碼:https://github.com/Zaniyar/sunshine/blob/master/app/src/main/java/ch/choix/sunshine/MainActivity.java – Suisse

+0

你永遠不會對你的新片段做任何事情。 http://stackoverflow.com/a/28208203/2308683 –

回答

0

我不得不改變 「的getContext()」 到「this.getActivity ()「在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); 
0

你應該將你的片段添加到new之後的你的主要活動,我的意思是 this file

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

也看到這個鏈接,瞭解更多信息

+0

這沒有奏效。沒有變化。 – Suisse

+0

也刪除此行'@TargetApi(Build.VERSION_CODES.M)'並重試 –

+0

不,它沒有幫助。 – Suisse