我开始学习Android应用程序开发,目前正在练习简单的应用程序。我正在编写包含listview的应用程序,我想用假数据填充它,但是当我在我的代码中使用findViewbyId()
时,应用程序会让我强行关闭但是当我将内容视图设置为我的片段而不是activity_main我没有强制关闭,但应用程序显示一个空列表。
这是我的代码:
package com.example.karen.please;
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] forecastArray =
{
"sunny",
"cloudy",
"asteroids",
"rainy",
"sunny"
};
List<String> weekforecast = new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter =
new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekforecast
);
ListView mylistview = (ListView)container.findViewById(R.id.listview_forecast); //screws upp in this line
mylistview.setAdapter(mForecastAdapter);
return inflater.inflate(R.layout.fragment_main, container, true);
}}
任何帮助都将不胜感激。
答案 0 :(得分:2)
您在试图夸大布局之前尝试查找视图...尝试在方法的顶部进行充气,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_main, container, true);
<all the other init code you have>
return myView;
}
答案 1 :(得分:0)
在使用findViewById
之前,您应该创建View
变量,使用inflate..
行,在您创建的findViewById
变量上使用View
,然后返回这一点。
这就是你的代码应该是这样的:
package com.example.karen.please;
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Instead of inflate and return instantly, store it in a variable,
// Then return at the end of the method.
View view = inflater.inflate(R.layout.fragment_main, container, true);
[...]
// Here, use findViewById on the View you have just inflated.
ListView mylistview = (ListView) view.findViewById(R.id.listview_forecast); //screws upp in this line
mylistview.setAdapter(mForecastAdapter);
// Return the view you created on the beginning.
return view;
}}
答案 2 :(得分:0)
首先你需要给你的布局充气......
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
...
ListView mylistview = (ListView)rootView.findViewById(R.id.listview_forecast);
...
答案 3 :(得分:0)
您应该从适当的教程开始,而不是混乱地添加您不理解的代码。从这里开始阅读:
Creating and Using Fragments
在你了解了它之后你会发现首先你需要通过id来扩展包含你想要找到的东西的布局,然后通过使用视图(定义布局)你可以找到所需的视图(listview等等) )。
答案 4 :(得分:-1)
ListView my listview = (ListView).findViewById(R.id.listview_forcast);
我认为应该是这样,代码中没有容器