我制作了自定义ListView
。我试图通过ListView
填充Arraylist
。我可以成功地将数据作为字符串发送,以填充ListView
,但不能填充ArrayList
。仅显示具有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
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;
}
}
答案 0 :(得分:2)
尝试通过迭代ArrayList
将每个Product
项添加到ArrayList
对象:
for(String row :arrlist) {
products.add(new Product(row, false));
}
将arrlist定义为String
ArrayList
而非通用类型List
:
ArrayList<String> arrlist = new ArrayList<String>();
答案 1 :(得分:1)
你的功能应该是
// Say Z[1] is "(' B', '1', '2', '-0', '+0.25', 'V', (05,245))\n"
import ast
print ast.literal_eval(Z[1])
// this should return (' B', '1', '2', '-0', '+0.25', 'V', (5, 245))