[英]Adding arraylist to custom listview
I have made a custom ListView
. 我做了一个自定义ListView
。 I'm trying to populate the ListView
by Arraylist
. 我正在尝试通过Arraylist
填充ListView
。 I can successfully send data as a string to populate the ListView
but not as ArrayList
. 我可以成功地将数据作为字符串发送以填充ListView
但不作为ArrayList
。 Only single row with all the values of arraylist
is being displayed. 仅显示具有arraylist
所有值的单行。
MainActivity 主要活动
public class MainActivity extends Activity {
ArrayList<Product> products = new ArrayList<Product>();
Adapter listviewAdapter;
List arrlist = new ArrayList();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrlist.add("1");
arrlist.add("2");
fillData();
listviewAdapter = new Adapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(listviewAdapter);
}
void fillData() {
products.add(new Product(arrlist.toString(),false)); //problem is here i suppose
}
}
Adapter.java Adapter.java
public class Adapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
Adapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
}
Product.java Product.java
public class Product {
String name;
boolean selected;
Product( String items, boolean _box) {
name = items;
selected = _box;
}
}
Try add each ArrayList
item to Product
object through iterating ArrayList
: 尝试通过迭代ArrayList
将每个ArrayList
项添加到Product
对象:
for(String row :arrlist) {
products.add(new Product(row, false));
}
Define arrlist as String
ArrayList
instead of generic type List
: 将arrlist定义为String
ArrayList
而不是泛型类型List
:
ArrayList<String> arrlist = new ArrayList<String>();
Your function should be 你的功能应该是
void fillData() {
products.add(new Product("1",false));
products.add(new Product("2",false));
products.add(new Product("3",false));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.