我有一个 ListView,它应该填充对象的 ArrayList。
ArrayList<BrowserClass> playListArr = new ArrayList<BrowserClass>();
这是 BrowserClass:
public class BrowserClass{
String musicName = null;
int musicId = 0;
BrowserClass(String Name, int Id)
{
musicName = Name;
musicId = Id;
}
public String getName()
{
return musicName;
}
public int getId()
{
return musicId;
}
}
为了填充 ListView,我使用以下代码:
ArrayAdapter<BrowserClass> plAdapter = new ArrayAdapter<BrowserClass>(this, android.R.layout.simple_list_item_1, playListArr);
myListView.setAdapter(plAdapter);
但是 listView 显示了一些垃圾值。我只需要显示名称(浏览器类中的 getname() )。我可以使用自定义 ListView 、BaseAdapter 来实现这一点。但我想在不使用 BaseAdapter 的情况下实现它。
最佳答案
像这样:
产品.java
public class Product {
private int id;
private String name;
private double price;
public Product(){
super();
}
public Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return this.id + ". " + this.name + " [$" + this.price + "]";
}
}
主要 Activity
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView1 = (ListView) findViewById(R.id.listView1);
Product[] items = {
new Product(1, "Milk", 21.50),
new Product(2, "Butter", 15.99),
new Product(3, "Yogurt", 14.90),
new Product(4, "Toothpaste", 7.99),
new Product(5, "Ice Cream", 10.00),
};
ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this,
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
}
}
关于Android:我们可以在不使用 BaseAdapter 的情况下使用对象的 ArrayList 加载 listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276081/