我有listview,我想按名称升序排序。我怎么能以编程方式做到这一点?
这是我的代码
public class InformationActivity extends AppCompatActivity {
private ArrayList<Actors> actorsList;
private ActorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
final ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
}
}
这里的ActorAdapter
public class ActorAdapter extends ArrayAdapter<Actors> {
private ArrayList<Actors> actorList;
private LayoutInflater vi;
private int Resource;
private ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.imgIcon);
holder.tvName = (TextView) v.findViewById(R.id.nama);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.tvName.setText(actorList.get(position).getName());
Picasso.with(this.getContext()).load(actorList.get(position).getImage()).placeholder(R.layout.progress).resize(110,110).error(R.mipmap.error).into(holder.imageview);
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
}
}
我是Android的初学者,非常感谢任何帮助。
提前致谢。
答案 0 :(得分:1)
使用此
Collections.sort(actorsList, new Comparator<Actors>() {
@Override
public int compare(Actors lhs, Actors rhs) {
return lhs.getName().compareTo(rhs.getName());
}});
答案 1 :(得分:0)
你可以这样做:
final ListView listview = (ListView)findViewById(R.id.list);
Collections.sort(actorsList, new Comparator<Actors>() {
/* This comparator will sort objects alphabetically. */
@Override
public int compare(Actors a1, Actors a2) {
// String implements Comparable
return (a1.name.toString()).compareTo(a2.name.toString());
}
});
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
您必须在setAdapter
方法之前对列表进行排序。