[英]How can I populate ArrayAdapter with objects?
I have a POJO like this: 我有一个这样的POJO:
public class Color {
private int id;
private int name;
//getter setter
}
In my AsyncTask I call the server and get bunch of these objects and then want to populate my list. 在我的AsyncTask中,我调用服务器并获取一堆这些对象,然后想要填充我的列表。 I do this by:
我这样做是:
@Override
protected String doInBackground(String... strings) {
colorsList = MyManager.INSTANCE.getService().getColors();
return null;
}
@Override
protected void onPostExecute(String file_url) {
setListAdapter(new ArrayAdapter<Color>(MyActivity.this,R.layout.list_black_text,R.id.name, colorsList));
}
list_black_text
looks like below: list_black_text
如下所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- hidden color id-->
<TextView
android:id="@+id/color_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!--color name-->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16dip"
android:textColor="#000000"
android:paddingTop="15dip"
android:paddingBottom="15dip"
android:paddingLeft="10dip"
android:textStyle="bold"/>
</RelativeLayout>
Question 题
When I run the app the list seems to be populated by objects so I see it being populated with stuff like 当我运行该应用程序时,该列表似乎由对象填充,因此我看到其中填充了以下内容
com.my.package.Color@2343fa0
com.my.package.Color@2343fa0
...
What do I need to change so that I can see the name of the color in the list? 我需要更改什么才能在列表中看到颜色的名称?
Note: I don't want to create a separate string array. 注意:我不想创建一个单独的字符串数组。 I have tried that and it works.
我已经尝试过了,而且行得通。 But I have additional requirement of being able to detect which
ID
color was clicked when the user clicks on a color name. 但是我还有其他要求,即当用户单击颜色名称时,能够检测到单击了哪个
ID
颜色。
The list is using the passed object's toString
method for display. 该列表使用传递的对象的
toString
方法进行显示。 So, if you want to display color names, just add a name variable, override the toString
method and return the name of the color. 因此,如果要显示颜色名称,只需添加一个名称变量,覆盖
toString
方法并返回颜色的名称。
public class Color {
private int id;
private int name;
private String strName;
public String toString(){return this.strName;}
//getter setter
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.