2016-08-05 6 views
0

Я создаю объекты из json с jackson, и я хочу показать эти объекты в expandableListView.Как сопоставить этот список объектов с расширяемым списком просмотров?

JSON выглядит следующим образом:

[ 
    { 
    "name": "Pete", 
    "profile_img": "img001", 
    "relations": { 
     "is_working_with": [], 
     "is_in_course_with": [ 
     { 
      "profile_img": "img002", 
      "name": "Jack" 
     } 
     ], 
     "is_friends_with": [ 
     { 
      "profile_img": "img003", 
      "name": "Stacey" 
     }, 
     { 
      "profile_img": "img002", 
      "name": "Jack" 
     } 
     ] 
    } 
    }, 
    { 
    "name": "Jack", 
    "profile_img": "img002", 
    "relations": { 
     "is_working_with": [{ 
     "profile_img": "img003", 
     "name": "Stacey" 
     }], 
     "is_in_course_with": [ 
     { 
      "profile_img": "img001", 
      "name": "Pete" 
     } 
     ], 
     "is_friends_with": [ 
     { 
      "profile_img": "img003", 
      "name": "Stacey" 
     }, 
     { 
      "profile_img": "img001", 
      "name": "Pete" 
     } 
     ] 
    } 
    } 
] 

И мои Java классы:

public class Student { 
    @JsonProperty("name") 
    String name; 
    @JsonProperty("profile_img") 
    String profileImg; 
    @JsonProperty("relations") 
    Relations relations; 

    //Constructors 
    //Setter, Getter 
} 
public class Relations { 
    @JsonProperty("is_working_with") 
    List<IsWorkingWith> isWorkingWith; 
    @JsonProperty("is_friends_with") 
    List<IsFriendsWith> isFriendsWith; 
    @JsonProperty("is_in_course_with") 
    List<IsInCourseWith> isInCourseWith; 

    //Constructors 
    //Setter, Getter 
} 
public class IsWorkingWith { 
    @JsonProperty("name") 
    String name; 
    @JsonProperty("profile_img") 
    String profileImg; 
} 
public class IsFriendsWith { 
    @JsonProperty("name") 
    String name; 
    @JsonProperty("profile_img") 
    String profileImg; 
} 
public class IsInCourseWith { 
    @JsonProperty("name") 
    String name; 
    @JsonProperty("profile_img") 
    String profileImg; 
} 

Я пытался продлить BaseExpandableListAdapter, и я получил это работает для представлений группы, но, как я укажите, какой атрибут моего объекта Student представляет дочерние элементы в списке.

В основном я хочу, глядя, как это:

list mockup

Как я должен создавать элементы в представлении ребенка?

ответ

0

Учитывая, что вы проиллюстрировали свой ExpandableListView, дети являются членами класса «Отношения». У вас есть дополнительное измерение в том, что каждый член класса отношений имеет свой собственный список.

Во-первых, давайте исправим свои определения классов:

public class Relations { 
    @JsonProperty("is_working_with") 
    List<Person> isWorkingWith; 
    @JsonProperty("is_friends_with") 
    List<Person> isFriendsWith; 
    @JsonProperty("is_in_course_with") 
    List<Person> isInCourseWith; 
} 

public class Person { 
    @JsonProperty("name") 
    String name; 
    @JsonProperty("profile_img") 
    String profileImg; 
} 

Если каждое отношение имеет свои собственные свойства, то есть лицо, в-конечно-с имеет свойство для курса они разделяют, надеюсь ваши JSON аннотаций может иметь дело с отдельный подкласс Person.

Так просто для примера возьмем getChildrenCount()

@Override 
    public int getChildrenCount(int groupPosition) { 
     return 3; // because every student has three types of relations 
    } 

Теперь вы подошли к более сложной части. У вас есть единственный ребенок, у которого есть список. Таким образом, представление ребенка должно обрабатывать различное количество Лиц. Для этого есть разные варианты, но если бы мне пришлось выбирать, я бы сделал дочерью представление горизонтального RecyclerView.

@Override 
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) { 

     // first let's handle the model stuff 
     Student student = (Student) getGroup(groupPosition); // would need to be implemented 
     List<Person> persons; 
     switch (childPosition) { 
     case 0: 
      persons = student.isWorkingWith; 
      break; 
     case 1: 
      persons = student.isFriendsWith; 
      break; 
     case 2: 
      persons = student.isInCourseWith; 
      break; 
     } 

     // now set up the view/adapter 
     RecyclerView recyclerView; 
     PersonAdapter adapter; // you would need to write this 
     if (view == null) { 
      view = LayoutInflater.from(mContext).inflate(R.layout.child, parent, false); 
      recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview); 
      view.setTag("recyclerview", recyclerView); 
      adapter = new PersonAdapter(parent.getContext()); // no data yet 
      view.setTag("adapter", adapter); 
      recyclerView.setLayoutManager(new LinearLayoutManager(parent.getContext(), LinearLayoutManager.HORIZONTAL, false); 
      recyclerView.setAdapter(adapter); 
     } else { 
      recyclerView = (RecyclerView) view.getTag("recyclerview"); 
      adapter = (PersonAdapter) view.getTag("adapter"); 
     } 

     adapter.setData(persons); // this method needs to call notifyDataSetChanged() 

     return view; 
    } 

Таким образом, вы получаете вложенные виды на основе адаптеров.

Вместо RecyclerView, вы можете добавить/удалить ваши взгляды Person динамически (не рекомендуется), или вы могли бы раздуть горизонтальную LinearLayout, которая имела дюжину вид человека, то скрыть мнения вы не в конечном итоге с помощью. Но подход RecyclerView немного более прост.

В любом случае, надеюсь, этого достаточно, чтобы вы начали.

Смежные вопросы