2016-01-30 119 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