I have ArrayList
of a class of mine that contains String
variables and integers, such as a name and punctuation. When viewing through Adapter
I'd like the list to have the punctuation in descending order, but I have not found how I do it. Does anyone know how? In case the text is the name the punctuation is the approval of the comment.
Below is the part where I create the list and the display:
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 was able 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);
}
}
class as well.
No fragment
just needed to call
Collections.sort(comentarios, C_Comentario.DESCENDING_COMPARATOR);