如何使用int和string对自定义适配器进行排序

时间:2017-04-02 20:22:29

标签: android sorting listview

我有一个列表视图,我想用四个类别排序列表视图,字符串名称(字母),字符串类别(按字母顺序),字符串日期(从新到旧),int Price(从99999到0)。我想在单击单选按钮时对列表视图进行排序。

当我想要列表视图时,这是我的费用活动

public class ExpensesActivity extends AppCompatActivity {

Button btnAddExpenses;
ListView lvExpenses;
CustomArrayAdapterExpenses adapter;
ArrayList<String> alExpensesName;
ArrayList<String> alExpensesPrice;
ArrayList<String> alExpensesCategory;
ArrayList<String> alExpensesDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expenses);

    final GlobalClass globalClass = (GlobalClass) getApplicationContext();
    final Bundle extras = getIntent().getExtras();

    btnAddExpenses = (Button) findViewById(R.id.btnAddExpenses);
    lvExpenses = (ListView) findViewById(R.id.lvExpenses);

    alExpensesName = globalClass.allTrips.get(extras.getInt("position")).getItemsString();
    alExpensesPrice = new ArrayList<>();
    for (Double i: globalClass.allTrips.get(extras.getInt("position")).getItemsCost()){
        alExpensesPrice.add(String.valueOf(i));
    }
    alExpensesCategory = globalClass.allTrips.get(extras.getInt("position")).getItemsCategory();
    alExpensesDate = globalClass.allTrips.get(extras.getInt("position")).getItemsDate();
    adapter = new CustomArrayAdapterExpenses(this, alExpensesName, alExpensesCategory , alExpensesPrice, alExpensesDate);
    lvExpenses.setAdapter(adapter);

    btnAddExpenses.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ExpensesActivity.this, AddExpensesActivity.class);
            intent.putExtra("position", extras.getInt("position"));
            finish();
            startActivity(intent);
        }
    });

    lvExpenses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ExpensesActivity.this, ExpenseActivity.class);
            intent.putExtra("position", extras.getInt("position"));
            intent.putExtra("positionExpense", position);
            finish();
            startActivity(intent);
        }
    });
}
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.rbName:
            if (checked) {
                /*
                Collections.sort(alExpensesName, new Comparator<String>()
                {
                    @Override
                    public int compare(String text1, String text2)
                    {
                        return text1.compareToIgnoreCase(text2);
                    }
                });
                adapter.notifyDataSetChanged();
                */
            }

                break;
        case R.id.rbPrice:
            if (checked){

            }
                break;
        case R.id.rbCategory:
            if (checked) {

            }
            break;
        case R.id.rbDate:
            if (checked) {

            }
            break;
    }
}

@Override
public void onBackPressed() {
    //super.onBackPressed();
    final Bundle extras = getIntent().getExtras();

    Intent intent = new Intent(ExpensesActivity.this, TripActivity.class);
    intent.putExtra("position", extras.getInt("position"));
    finish();
    startActivity(intent);
}
}

这是CustomArrayAdapterExpenses

public class CustomArrayAdapterExpenses extends BaseAdapter {

ArrayList<String> alExpensesName;
ArrayList<String> alExpensesPrice;
ArrayList<String> alExpensesCategory;
ArrayList<String> alExpensesDate;

Context mContext;

//constructor
public CustomArrayAdapterExpenses(Context mContext, ArrayList<String> alExpensesName, ArrayList<String> alExpensesCategory, ArrayList<String> alExpensesPrice, ArrayList<String> alExpensesDate) {
    this.mContext = mContext;
    this.alExpensesName = alExpensesName;
    this.alExpensesCategory = alExpensesCategory;
    this.alExpensesPrice = alExpensesPrice;
    this.alExpensesDate = alExpensesDate;
}

public int getCount() {
    return alExpensesName.size();
}

public Object getItem(int arg0) {
    return null;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View arg1, ViewGroup viewGroup) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.item_list_expenses, viewGroup, false);

    TextView tvExpensesName = (TextView) row.findViewById(R.id.tvExpensesName);
    TextView tvExpensesCategory = (TextView) row.findViewById(R.id.tvExpensesCategory);
    TextView tvExpensesPrice = (TextView) row.findViewById(R.id.tvExpensesPrice);
    TextView tvExpensesDate = (TextView) row.findViewById(R.id.tvExpensesDate);


    tvExpensesName.setText(alExpensesName.get(position));
    tvExpensesCategory.setText(alExpensesCategory.get(position));
    tvExpensesPrice.setText(alExpensesPrice.get(position));
    tvExpensesDate.setText(alExpensesDate.get(position));


    return row;
}
}

这是我的旅行班

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
private Calendar FirstDate;
private Calendar EndDate;
private int HowMuchDays;
private String SFirstDate, SEndDate;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public ArrayList<TraveledDay> TraveledDays = new ArrayList<>();
public ArrayList<Fuel> Fuels = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    final String Date;
    String Description;
    public Item(String name, double cost, String Category, String Date) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
        this.Date = Date;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
    public String getDate(){
        return Date;
    }
    public String getDescription(){ return Description; }
}

static class TraveledDay {
    final String Date;
    final int FirstKM;
    final int EndKM;
    final int KM;
    public TraveledDay(int FirstKM, int EndKM, String Date) {
        this.FirstKM = FirstKM;
        this.EndKM = EndKM;
        this.Date = Date;
        KM = EndKM - FirstKM;
    }
    @Override public String toString() {
        return this.Date + " (" + this.KM + ")";
    }
    public int getFirstKM(){
        return FirstKM;
    }
    public int getEndKM(){
        return EndKM;
    }
    public int getKM(){
        return KM;
    }
    public String getDate(){
        return Date;
    }
}

static class Fuel {
    final String Date;
    final int CurrentKM;
    final int LastKM;
    final int SumKM;
    final double SumLiter;
    final double LiterPrice;
    final double SumPrice;

    public String getDate() {
        return Date;
    }

    public int getCurrentKM() {
        return CurrentKM;
    }

    public int getLastKM() {
        return LastKM;
    }

    public int getSumKM() {
        return SumKM;
    }

    public double getSumLiter() {
        return SumLiter;
    }

    public double getLiterPrice() {
        return LiterPrice;
    }

    public double getSumPrice() {
        return SumPrice;
    }

    public Fuel(String Date, int CurrentKM, int LastKM, int SumKM, double SumLiter, double LiterPrice, double SumPrice) {
        this.Date = Date;
        this.CurrentKM = CurrentKM;
        this.LastKM = LastKM;
        this.SumKM = SumKM;
        this.SumLiter = SumLiter;
        this.LiterPrice = LiterPrice;
        this.SumPrice = SumPrice;
    }
    @Override public String toString() {
        return this.Date + " (" + this.SumKM + ")";
    }
}

public Trip(String name, Calendar FirstDate, Calendar EndDate, String SFirstDate, String SEndDate) {
    this.name = name;
    this.FirstDate = FirstDate;
    this.EndDate = EndDate;
    HowMuchDays = (int)((EndDate.getTime().getTime() - FirstDate.getTime().getTime()) / (1000 * 60 * 60 * 24));
    this.SEndDate = SEndDate;
    this.SFirstDate = SFirstDate;
    this.expanses = new HashMap<String,List<Item>>();
    ExpensesCategory.add("כרטיסי טיסה");
    ExpensesCategory.add("לינה");
    ExpensesCategory.add("תחבורה");
    ExpensesCategory.add("אוכל");
    ExpensesCategory.add("אתרים");
    ExpensesCategory.add("שונות");
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}
public Calendar getFirstDate(){
    return FirstDate;
}
public Calendar getEndDate(){
    return EndDate;
}
public Integer getHowMuchDays(){
    return HowMuchDays;
}
public String getSFirstDate(){
    return SFirstDate;
}
public String getSEndDate(){
    return SEndDate;
}


/** Register a new expanse to the trip. */
public void add(String item, double cost, String category, String Date) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category, Date) );
}

public void addTraveledDay(int FirstKM, int EndKM, String Date) {
    ArrayList<TraveledDay> list = TraveledDays;
    list.add( new TraveledDay(FirstKM, EndKM, Date) );
}

public void removeTraveledDay(int index) {
    ArrayList<TraveledDay> list = TraveledDays;
    list.remove(index);
}

public ArrayList<Integer> getTraveledFirstKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (TraveledDay traveledDay : TraveledDays){
        listInteger.add(traveledDay.getFirstKM());
    }
    return listInteger;
}

public ArrayList<Integer> getTraveledEndKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (TraveledDay traveledDay : TraveledDays){
        listInteger.add(traveledDay.getEndKM());
    }
    return listInteger;
}

public ArrayList<Integer> getTraveledKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (TraveledDay traveledDay : TraveledDays){
        listInteger.add(traveledDay.getKM());
    }
    return listInteger;
}

public ArrayList<String> getTraveledDate() {
    ArrayList<String> listString = new ArrayList<String>();
    for (TraveledDay traveledDay : TraveledDays){
        listString.add(traveledDay.getDate());
    }
    return listString;
}

public ArrayList<String> getFuelDate() {
    ArrayList<String> listString = new ArrayList<String>();
    for (Fuel fuel : Fuels){
        listString.add(fuel.getDate());
    }
    return listString;
}

public ArrayList<Integer> getFuelCurrentKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listInteger.add(fuel.getCurrentKM());
    }
    return listInteger;
}

public ArrayList<Integer> getFuelLastKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listInteger.add(fuel.getLastKM());
    }
    return listInteger;
}

public ArrayList<Integer> getFuelSumKM(){
    ArrayList<Integer> listInteger = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listInteger.add(fuel.getSumKM());
    }
    return listInteger;
}

public ArrayList<Double> getFuelSumLiter(){
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listDouble.add(fuel.getSumLiter());
    }
    return listDouble;
}

public ArrayList<Double> getFuelLiterPrice(){
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listDouble.add(fuel.getLiterPrice());
    }
    return listDouble;
}

public ArrayList<Double> getFuelSumPrice(){
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Fuel fuel : Fuels){
        listDouble.add(fuel.getSumPrice());
    }
    return listDouble;
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<String> getItemsDescription() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getDescription());
    }
    return listString;
}

public ArrayList<String> getItemsDate() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getDate());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
}
}

这是我的全球课程

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
}

public ArrayList<Integer> allTripsHowMuchDate() {
    ArrayList<Integer> allTripsString = new ArrayList<>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getHowMuchDays());
    }
    return allTripsString;
}

public ArrayList<String> allTripsSFirstDate() {
    ArrayList<String> allTripsString = new ArrayList<>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getSFirstDate());
    }
    return allTripsString;
}

public ArrayList<String> allTripsSEndDate() {
    ArrayList<String> allTripsString = new ArrayList<>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getSEndDate());
    }
    return allTripsString;
}


public void saveList(Context context, List<Trip> list) {

    String PREFS_NAME = "PRODUCT_APP";
    String KEY_NAME = "KEY_NAME";

    SharedPreferences settings;
    SharedPreferences.Editor editor;

    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    Gson gson = new Gson();
    String jsonlist = gson.toJson(list);

    editor.putString(KEY_NAME, jsonlist);

    editor.commit();
}
public void loadList(Context context){
    String PREFS_NAME = "PRODUCT_APP";
    String KEY_NAME = "KEY_NAME";

    SharedPreferences settings;

    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    Gson gson = new Gson();
    String jsonlist = settings.getString(KEY_NAME, "");

    if (jsonlist.isEmpty()) {
        allTrips = new ArrayList<>();
    } else {
        Type type = new TypeToken<ArrayList<Trip>>(){}.getType();
        allTrips = gson.fromJson(jsonlist, type);
    }
}
}

1 个答案:

答案 0 :(得分:0)

这个问题有两个解决方案: 1.简单的解决方法是创建一个具有4个属性的自定义类:名称,类别,价格和展开日期或使用现有的类项。将自定义对象数组传递给适配器。如果您尝试根据不同属性之间的任何键映射对此自定义对象进行排序,那么它将永远不会丢失并且它可以满足您的问题。在RadioButtonClick侦听器上对自定义数组进行排序并更新适配器并通知。

  1. 尝试根据一个键同时对4个阵列进行排序。就像你想根据名称排序一样,尝试在名称数组上实现选择排序,并在所有四个数组中交换交换元素,以维护所有四个数组之间的映射。在该解决方案中,分类的性能不佳。要实现此功能,请参阅How to sort multiple ArrayLists based off order of another?