gpt4 book ai didi

java - 将 arraylist 添加到自定义 ListView

转载 作者:可可西里 更新时间:2023-10-31 22:04:11 25 4
gpt4 key购买 nike

我制作了一个自定义的 ListView。我正在尝试通过 Arraylist 填充 ListView。我可以将数据作为字符串成功发送以填充 ListView,但不能作为 ArrayList。仅显示包含 arraylist 的所有值的单行。

主 Activity

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

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

public class Product {
String name;
boolean selected;

Product( String items, boolean _box) {
name = items;
selected = _box;
}
}

最佳答案

尝试通过迭代 ArrayList 将每个 ArrayList 项添加到 Product 对象:

for(String row :arrlist) {
products.add(new Product(row, false));
}

将 arrlist 定义为 String ArrayList 而不是泛型 List:

ArrayList<String> arrlist = new ArrayList<String>(); 

关于java - 将 arraylist 添加到自定义 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30028413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com