我正在从字符串数组创建简单的listview。我看过很多教程都说同样只有3行足以使它工作。我正在做同样但仍然得到NPE,几乎对此问题感到沮丧。无法弄清楚什么是错的,请帮助我。
我的代码在这里:
Mainfiest :
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
MainActivity.java
public class MainActivity extends Activity {
ListView lv;
String[] days = new String[] { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, days);
lv.setAdapter(adapter);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
答案 0 :(得分:1)
嘿,你错了配置代码。在这里你将listview放在片段xml中并在mainactivity类中编写代码,这样你就必须删除你的片段xml并将你的片段xml代码替换为mainactivity xml并删除下面的代码
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
来自onCreate()的
OR
在片段类的OnCreateView中初始化Listview
public static class PlaceholderFragment extends Fragment {
ListView lv;
String[] days = new String[] { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"};
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
lv = (ListView) view.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(GetActivity(),
android.R.layout.simple_list_item_1, days);
lv.setAdapter(adapter);
return rootView;
}
}
多数民众赞成......
答案 1 :(得分:0)
更改
setContentView(R.layout.activity_main);
到
setContentView(R.layout.fragment_main);
答案 2 :(得分:0)
您在活动中显示新片段。
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
但是listview是在主要活动布局中声明的。 因此,要查看列表视图,只需对上面的代码进行评论,然后查看。
答案 3 :(得分:0)
您需要将“String [] days”中的项添加到“适配器”中,您可以使用方法adapter.add或adapter.addAll将项添加到ArrayAdapter。有关详细信息,请参阅此处的简单listView示例