【问题标题】:Sort listview for 2 conditions为 2 个条件排序列表视图
【发布时间】:2015-12-24 03:21:53
【问题描述】:

我可以一次对我的列表视图进行 2 个条件排序吗?我有 4 行:标题、描述、图像的 url 和 pinned。我必须在顶部显示 pinned==true 的记录,然后我必须按字母顺序对标题行进行排序,在 pinned==true 行之后显示。我该怎么做?MainActivity 和 Adapter 放在下面。 主要活动:

public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
    Intent intent;
    private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String IMAGE = "image";
    private static final String PINNED = "pinned";

    ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String,String>> bdList = new ArrayList<HashMap<String, String>>();
   ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actbar = getActionBar();
        actbar.setDisplayShowHomeEnabled(false);
        actbar.setDisplayShowTitleEnabled(false);
        actbar.setDisplayUseLogoEnabled(false);
        lv=(ListView) findViewById(android.R.id.list);
        LayoutInflater mInflater =LayoutInflater.from(MainActivity.this);
        View mcustomview = mInflater.inflate(R.layout.customactionbar, null);
        ImageButton imgbutt =(ImageButton)mcustomview.findViewById(R.id.actbarimagebutton);
        imgbutt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ProgressTask(MainActivity.this).execute();
            }

        });
        actbar.setCustomView(mcustomview);
        actbar.setDisplayShowCustomEnabled(true);
        if(isNetworkConnected()==true) {
            new ProgressTask(MainActivity.this).execute();
            ForItemClick();
        }
        else {
            try {
                dbHelper = new SqlHelper(MainActivity.this);
               WithoutInternetItemClick();
                imgbutt.setClickable(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            displaysavedlv();

        }



    }

    private class ProgressTask extends AsyncTask<String,Void,Boolean> {
        private ProgressDialog dialog;
        private ListActivity activity;
        private Context context;

        public ProgressTask(MainActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
            try {
                dbHelper = new SqlHelper(MainActivity.this);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        protected void onPreExecute(){
           this.dialog.setMessage("Progress start");
           this.dialog.show();
        }
        protected void onPostExecute(final Boolean success){
            try{
       if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
            }
if(isNetworkConnected()==true) {
    CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, jsonlist, R.layout.list_item, new String[]{TITLE, DESCRIPTION}, new int[]{R.id.title, R.id.description});
    lv.setAdapter(adapter);
}else{
    displaysavedlv();
}


        }catch (final IllegalArgumentException e){e.printStackTrace();}
        }
        protected Boolean doInBackground(String... args) {

           JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);
            for(int i =0;i<json.length();i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtitle = c.getString(TITLE);
                    String vdescription = c.getString(DESCRIPTION);
                    String vimage = c.getString(IMAGE);
                    Boolean vpinned = c.getBoolean(PINNED);
                    dbHelper.open();
dbHelper.createEntry(vtitle, vimage, vdescription);

                    dbHelper.close();
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TITLE, vtitle);
                    map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
                    map.put(PINNED, String.valueOf(vpinned));
                    jsonlist.add(map);

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }
    public void ForItemClick(){

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = jsonlist.get(position).get("title");
                String description1 = jsonlist.get(position).get("description");
                String url1 = jsonlist.get(position).get("image");

                intent = new Intent(MainActivity.this, DetailInfo.class);


                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);


    }
});
    };
    private void displaysavedlv(){
        bdList = dbHelper.getAllData();
lv=(ListView) findViewById(android.R.id.list);
        CustomListAdapter adapter1 = new CustomListAdapter(MainActivity.this,bdList,R.id.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
        lv.setAdapter(adapter1);


    }
    public void WithoutInternetItemClick(){
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = bdList.get(position).get("title");
                String description1 = bdList.get(position).get("description");
                String url1 = bdList.get(position).get("image");
                intent = new Intent(MainActivity.this, DetailInfo.class);


                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);
            }
        });


    }
}

适配器:

public class CustomListAdapter extends SimpleAdapter {
    private static final String IMAGE = null;
private final Activity context;
private ArrayList<HashMap<String, String>> result;
    public CustomListAdapter(Activity context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
        super(context,data,resource,from,to);
        // TODO Auto-generated constructor stub

this.result = data;
        this.context = context;
    }

    public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.list_item, null, true);


        ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
TextView title = (TextView) rowView.findViewById(R.id.title);
        title.setText(result.get(position).get("title"));
TextView description = (TextView) rowView.findViewById(R.id.description);
        description.setText(result.get(position).get("description"));
String url = result.get(position).get("image");
          Picasso.with(context)
                .load(url).into(imageView);


        return rowView;

    }


}

【问题讨论】:

  • 设置一个Comparator 来实现您的业务规则,然后使用Comparator 设置sort() 您的模型集合。

标签: android sorting listview android-listview


【解决方案1】:

将 Comparable 扩展到您的对象 覆盖等于和比较

@Override
public boolean equals(Object2 obj) {
    if (obj == null)
        return false;
    if (!(obj instanceof Messages))
        return false;
    Object1 u = (Object1) obj;

    return this.gettitle() == u.gettitle()
}

@Override
public int compareTo(Object2 obj) {
    return String.valueOf(this.title).compareTo(obj.title);
}

【讨论】:

    【解决方案2】:

    如果我关注你的问题,那么你可以做这样的事情。

    您甚至可以在 bean 本身中定义比较器,以便您可以重复使用它们,而不是每次都重新创建它们:

    public class Contact {
    
        private String name;
        private String phone;
        private Address address;
    
        // ...
    
        public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
            public int compare(Contact one, Contact other) {
                return one.phone.compareTo(other.phone);
            }
        };
    
        public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
            public int compare(Contact one, Contact other) {
                return one.address.compareTo(other.address);
            }
        };
    
    }
    

    可以这样使用:

    List<Contact> contacts = new ArrayList<Contact>();
    // Fill it.
    
    // Sort by address.
    Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);
    
    // Sort later by phone.
    Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
    

    更多详情请见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多