3
I have a ArrayList
of a class of mine that contains variables String
and integers, as a name and punctuation. When I display it through a Adapter
I would like the list to be in descending order, but I couldn’t find how to do it. Does anyone know how? In case the text is the name the score is the approval of the comment.
Below is the part where I create the list and display it:
public class F_ListaComentarios extends ListFragment {
C_Comentario comentario;
private List<C_Comentario> comentarios;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comentarios = new ArrayList<C_Comentario>();
preencherListaComentarios(comentarios);
if (comentarios != null) {
adapter = new P_ComentarioAdapter(getActivity(), comentarios);
setListAdapter(adapter);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.f_lista_comentarios, null, false);
return (view);
}
public void preencherListaComentarios(ArrayList<C_Comentario> comentarios) {
C_Comentario comentario = new C_Comentario();
comentario.setTexto("AA");
comentario.setAprovado(0);
comentarios.add(comentario);
C_Comentario comentario2 = new C_Comentario();
comentario.setTexto("AV");
comentario.setAprovado(2);
comentarios.add(comentario);
C_Comentario comentario3 = new C_Comentario();
comentario.setTexto("AA");
comentario.setAprovado(1);
comentarios.add(comentario);
C_Comentario comentario4 = new C_Comentario();
comentario.setTexto("AA");
comentario.setAprovado(5);
comentarios.add(comentario);
}
}
I managed to solve by implementing Comparable<C_Comentario>
to my class C_Comentario
and adding
public static final Comparator<C_Comentario> DESCENDING_COMPARATOR = new Comparator<C_Comentario>() {
// Overriding the compare method to sort the age
public int compare(C_Comentario c, C_Comentario c1) {
return c1.aprovado - c.aprovado;
}
};
e
@Override
public int compareTo(C_Comentario c) {
return (this.titulo).compareTo(c.titulo);
}
}
the class also.
In the fragment
I just had to call
Collections.sort(comentarios, C_Comentario.DESCENDING_COMPARATOR);
Put the code on how you’re doing so we can see and be of better help
– César Sousa