我正在尝试设置一个 ListView 并且我能够使用一个简单的 String[] 数组来完成它,正如您在代码中看到的那样。
后来,我注释掉了 Array 并使用了 List
当我想使用 List(因为我需要操作内容)并且无法动态更改简单的 Array 时,我的问题就开始了。当我使用 List 时,我在创建 ArrayAdapter 时得到 NullPointerException,但我不知道为什么。
我在 ArrayAdapter 的文档中读到它被 6 个不同的构造函数重载,其中一个是
ArrayAdapter(上下文上下文,int资源,列表对象)
为什么我会收到 NullPointerException?
我应该怎么做才能使它与列表而不是数组一起使用?
提前致谢!
public class MainActivity extends Activity implements OnItemClickListener {
ListView l;
// String[] days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
List<String> days;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
days.add(0, "Sunday");
days.add(1, "Monday");
days.add(2, "Tuesday");
days.add(3, "Wednesday");
days.add(4, "Thursday");
days.add(5, "Friday");
days.add(6, "Saturday");
l = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, days);
l.setAdapter(adapter);
l.setOnItemClickListener(this);
}
@Override
public void onItemClick(
AdapterView<?> adapterView, // ListView that was clicked
View view, // Reference to the row that was clicked (each row is a TextView)
int i, // position
long l) { // id of the TextView that was clicked
Toast.makeText(this, days.get(i) + " " + i, Toast.LENGTH_LONG).show();
}
}