是否可以像这样在适配器中添加2个对象类?
public Adapter(Context context, List<ObjectItem> objectItem, List<ObjectItem2> objectItem2) {
}
这是示例代码:我要用嵌套的json数组解析json,所以第一个json就像:
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
ObjectItem item = new ObjectItem();
item.setUserid(userid);
item.setProfilePic(profile_photo);
item.setName(profile_name);
int jKomen = c.getJSONArray("comment_note").length();
if(c.getJSONArray("comment_note").length() > 0) {
commentNoteJsonArr = c.getJSONArray("comment_note");
for (int j = 0; j < commentNoteJsonArr.length(); j++) {
JSONObject d = commentNoteJsonArr.getJSONObject(j);
String pName2 = d.isNull("profile_name") ? null : d.getString("profile_name");
item.setName2(pName2);
String pComment2 = d.isNull("content_comment") ? null : d.getString("content_comment");
item.setComment2(pComment2);
}
}
item.setLevel(Level.LEVEL_ONE);
Items.add(item);
}
这是在解析上面的json代码之后的第二个代码:
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
ObjectItem2 item2 = new ObjectItem2();
item2.setId(c.getString("id_note"));
int jKomen = c.getJSONArray("comment_note").length();
if(c.getJSONArray("comment_note").length() > 0) {
commentNoteJsonArr = c.getJSONArray("comment_note");
for (int j = 0; j < commentNoteJsonArr.length(); j++) {
JSONObject d = commentNoteJsonArr.getJSONObject(j);
item2.setUserid(d.getString("userid"));
item2.setProfilePic(d.getString("profile_photo"));
item2.setName(d.getString("profile_name"));
}
}
item2.setLevel(Level.LEVEL_TWO);
Items2.add(item2);
}
适配器:
adapter.notifyDataSetChanged();
所以,我想将对象Items和Items2添加到适配器。那么我应该怎么做才能清除它? 提前致谢
答案 0 :(得分:0)
创建界面
public interface DispayItem {
}
现在创建实现DispayItem接口的类
public class Class1 implements DispayItem {
private int id;
private String label;
private Class1 () {
}
public static Class1 create( int id, String label ) {
Class1 section = new Class1 ();
section.setLabel(label);
return section;
}
}
的Class2
public class Class2 implements DispayItem {
private int id;
private String label;
private Class2 () {
}
public static Class2 create( int id, String label ) {
Class2 section = new Class2 ();
section.setLabel(label);
return section;
}
}
添加可以将其用作
的项目 DisplayItem[] displayItem= new DisplayItem[] {
Class1.create( 100, "Class1"),
Class2.create(101,"Class2"),
};
您的适配器中的
public MyAdapter(Context context, int textViewResourceId, DisplayItem[] objects ) {
super(context, textViewResourceId, objects);
this.inflater = LayoutInflater.from(context);
}
使用getView int adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
DisplayItem displayItem = this.getItem(position);
if(displayItem instanceof Class1){
//do work for class 1
view = getItemView(convertView, parent, menuItem );
}
else if(displayItem instanceof Class2){
//do work for class 2
view = getItemView(convertView, parent, menuItem );}
}
return view;}