簡體   English   中英

Android列表視圖着色項

[英]Android List view coloring items

我有2個字段的JSON-名稱和性別。 如果性別是男性,我想將每個名稱塗成藍色,如果性別是女性,則將粉紅色塗成粉紅色。

這是我的代碼

ArrayList feedList1 = new ArrayList<HashMap<String, Object>>();


for (int i = 0; i < data.length(); i++) {
    HashMap<String, Object> hm;
    hm = new HashMap<String, Object>();

    hm.put("id", data.getJSONObject(i).getString("id").toString());
    hm.put("gender", data.getJSONObject(i).getString("gender").toString());
    hm.put("name", data.getJSONObject(i).getString("name").toString());
    feedList1.add(hm);
    SimpleAdapter adapter = new SimpleAdapter(feedList.getContext(), feedList1, R.layout.list,
            new String[] {"id","name"}, new int[] { R.id.personId, R.id.personName }){
        @Override
        public void setViewText(TextView v, String text) {
            super.setViewText(v, text);
            if (v.getId() == R.id.personName) {

                if (/* how to get gender of this person*/) 
                    v.setTextColor(R.color.female); 
                else
                    v.setTextColor(R.color.male);
            }
        }

    };

    feedList.setAdapter(adapter);
    feedList.setChoiceMode(feedList.CHOICE_MODE_SINGLE);
}

請告訴我如何在IF語句中添加性別。

如果不創建自己的自定義適配器,則無法這樣做,因此可以覆蓋getView。 檢查以下代碼,並使用CustomAdapter而不是SimpleAdapter

class CustomAdapter extends SimpleAdapter {

    public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        Map<String, Object> item = (Map<String, Object>) getItem(position);
        if ("male".equals(item.get("gender").toString())) {
            view.setBackgroundColor(R.color.male);
        } else {
            view.setBackgroundColor(R.color.female);
        }

        return view;
    }
}

我認為您必須在使用此字符串之前先獲取String值。

String gender = hm.get("gender");
if (gender.equals("male"))
    dosomething;
else
    doAnotherThing;

我想你也必須把hm變成最終的!!! 希望對您有幫助!!

您應該重寫getView方法而不是setViewText。 但是,如果您非常希望使用setViewText,則可以將對象的名稱設置為“ thomas&man”,然后用分隔符“&”將字符串划分為字符串數組,而數組的第二項將是性別。 但是更好的使用是重寫getView方法,這是正確的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM