如何将元素动态添加到类中。我有一个列表视图组件和String变量中的信息列表。
它们由星号和#分隔。
我需要ListView
的适配器并使用此方法。
静态方法还可以。
但是动态方法不起作用。
这是我的代码:
public class transModel{
public String DateTime;
public String Action;
public String Amount;
public String DestAccount;
public transModel(String DateTime, String Action, String Amount, String DestAccount){
this.DateTime = DateTime;
this.Action = Action;
this.Amount = Amount;
this.DestAccount = DestAccount;
}
}
class Mylistadapter extends BaseAdapter{
transModel[] transModels;
public Mylistadapter (transModel[] transModels){
this.transModels = transModels;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.report_list,null);
……
return view1;
}
}
.
.
/////////////// Main program ///////////////////
result1 = “a#b#c#d * e#f#g#h * i#j#k#l”;
String[] items = result1.split(Pattern.quote("*"));
String[] items1;
transModel[] transModels = null;
transModel tt = new transModel("","","","");
for (String item : items) {
items1 = item.split(Pattern.quote("#"));
tt.DateTime = items1[0];
tt.Action = items1[1];
tt.Amount = items1[2];
tt.DestAccount = items1[3];
// transModels = new transModel[]{tt};
}
ListView lview = (ListView) view.findViewById(R.id.list_trans);
lview.setAdapter(new Mylistadapter(transModels));
/*
Static way :
transModel tmodel1 = new transModel(“a”,”b”,”c”,”d”);
transModel tmodel2 = new transModel(“e”,”f”,”g”,”h”);
transModel tmodel3 = new transModel(“i”,”j”,”k”,”l”);
transModel[] transModels = new transModel[]{tmodel1,tmodel2,tmodel3};
*/
答案 0 :(得分:0)
您将项目错误地添加到了数组中。以下代码不正确:
String[] items = result1.split(Pattern.quote("*"));
String[] items1;
transModel[] transModels = null;
transModel tt = new transModel("","","","");
for (String item : items) {
items1 = item.split(Pattern.quote("#"));
tt.DateTime = items1[0];
tt.Action = items1[1];
tt.Amount = items1[2];
tt.DestAccount = items1[3];
// transModels = new transModel[]{tt};
}
首先,您永远不会用以下方法初始化数组大小:
transModel[] transModels = null;
第二,您永远不会在每个循环中都设置项目。
要解决此问题,您需要使用以下内容初始化数组的大小:
transModel[] transModels = new TransModel[10];
然后按位置设置每个项目。
这里是示例代码:
String[] items = result1.split(Pattern.quote("*"));
// initialize the length of transModel by the length of items.
transModel[] transModels = new transMode[items.length];
// use traditional for loop so we can use the item index.
for (int i = 0; i < items.length; i++) {
transModel tt = new transModel("","","","");
String[] items1 = items[i].split(Pattern.quote("#"));
tt.DateTime = items1[0];
tt.Action = items1[1];
tt.Amount = items1[2];
tt.DestAccount = items1[3];
// set the transModel to the array with specific index.
transModels[i] = tt;
}
// now you have the array properly populated.
ListView lview = (ListView) view.findViewById(R.id.list_trans);
lview.setAdapter(new Mylistadapter(transModels));