如何动态地将图标设置为ListItems?

时间:2013-11-25 09:55:55

标签: android listview sharedpreferences

我有一个ListView,其列表项来自共享首选项的“字符串”。现在我必须设置两个图标“成功”和“失败”,从字符串中识别出这些关键字“成功”和“失败”。但设置它时要么将“成功”图标设置为所有列表项,要么将“失败”图标设置为所有原因,因为字符串包含两者。任何想法我如何识别每个列表项并为它们设置图标?以下是我的代码:

我从共享首选项中检索“oldlistitems”和“newlistitems”字符串并尝试将图标设置为列表项的类

public class EntryAdapterLog extends ArrayAdapter<Item> {

    private Context context;
    private ArrayList<Item> items;
    private LayoutInflater vi;

    public EntryAdapterLog(Context context,ArrayList<Item> items) {
        super(context,0, items);
        this.context = context;
        this.items = items;
        vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


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

        final Item i = items.get(position);
        if (i != null) {
            if(i.isSection()){
                SectionItem si = (SectionItem)i;
                v = vi.inflate(R.layout.list_item_section, null);

                v.setOnClickListener(null);
                v.setOnLongClickListener(null);
                v.setLongClickable(false);

                final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
                sectionView.setText(si.getTitle());
            }else{

                String oldlistitems = LogListView.first;
                String newlistitems = LogListView.title;
                Log.d("LOG", "ABCD : " + oldlistitems);
                Log.d("LOG", "DEFG : " + newlistitems);

                EntryItem ei = (EntryItem)i;
                v = vi.inflate(R.layout.list_item_entry_log, null);
                final TextView title = (TextView)v.findViewById(R.id.list_item_entry_title);
                final TextView subtitle = (TextView)v.findViewById(R.id.list_item_entry_summary);
                final ImageView imageicon = (ImageView)v.findViewById(R.id.list_item_entry_drawable);

                if(title != null) {
                    title.setText(ei.title);
                }
                if(subtitle != null){
                    subtitle.setText(ei.subtitle);
                }
                //HERE IS PROCESS OF SETTING ICONS
                if ((oldlistitems !=null && oldlistitems.contentEquals("Sync Successful")) || (newlistitems != null && newlistitems.contentEquals("Sync Successful"))){
                    imageicon.setImageResource(R.drawable.ok);
                }
                else {
                    imageicon.setImageResource(R.drawable.wrong);
                }

            }
        }
        return v;
    }

}

我设置共享偏好的类

public class LogListView extends ListActivity {
    /** Called when the activity is first created. */
    static String newString;
    private static EntryAdapterLog adapter;
    int clickCounter = 0;
    static ArrayList<Item> items = new ArrayList<Item>();
    static SharedPreferences preferences = null;
    private static Context context = null;
    static StringTokenizer tokens;
    static String first;
    private static String second;
    private JSONArray jsonarry = null;
    static String saveitems;
    private JSONObject jsonobject = null;
    private String subtitle;
    static String title;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        adapter = new EntryAdapterLog(this, items);
        // items.add(new SectionItem("Log Report"));
        setListAdapter(adapter);

        if (adapter.getCount() != 0) {
            // Do nothing Adapter has value
        } else {
            retreiveItems();
        }

    }

    // Method which will handle dynamic insertion
    public static void addItems() {

        preferences = context.getSharedPreferences("LOG",android.content.Context.MODE_PRIVATE);
        newString = preferences.getString("log", "");

        tokens = new StringTokenizer(newString, ",");
        first = tokens.nextToken();
        second = tokens.nextToken();

        items.add(new EntryItem(first, second));

        adapter.notifyDataSetChanged();

    }
    // Method which will handle dynamic insertion ends

    @Override
    protected void onDestroy() {
        super.onDestroy();
        saveItems();
    }

    // Save ListItems if restarted
    protected static void saveItems() {
        SharedPreferences prefs = context.getSharedPreferences("prefName",Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putString("myList", new Gson().toJson(items).toString());
        editor.apply();
        Log.d("LOG", "Saved Items : " + items);
    }
    // Save ListItems if restarted ends

    // Retrieve ListItems if restarted
    protected void retreiveItems() {
        preferences = context.getSharedPreferences("prefName",android.content.Context.MODE_PRIVATE);
        saveitems = preferences.getString("myList", "");
        Log.d("LOG", "Retreived Items : " + saveitems);

        try {
            jsonarry = new JSONArray(saveitems);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (jsonarry == null || jsonarry.length() == 0) {
            return;                                                                        //This checks before setting adapter onCreate if adapter is null
        }

        for (int i = 0; i < jsonarry.length(); i++) {

            try {
                jsonobject = jsonarry.getJSONObject(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // get all values here from JSONObject
            title = jsonobject.optString("title");
            subtitle = jsonobject.optString("subtitle");

            items.add(new EntryItem(title, subtitle));
            adapter.notifyDataSetChanged();

        }

    }
    // Retrieve ListItems if restarted ends

    // Counter for amount of period of time before flusing adapter
    protected void flushList(){

    }
    // Counter for amount of period of time before flusing adapter ends

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        if (!items.get(position).isSection()) {
            items.get(position);
            Toast.makeText(this, "You clicked " + position, Toast.LENGTH_SHORT).show();

        }

        if (position == 9) {

        }

        super.onListItemClick(l, v, position, id);
    }




}

此致

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要更新每个项目的图标,具体取决于该项目的sync successfulsync failed

你应该做这样的事情(相应地更新你的代码):

//HERE IS PROCESS OF SETTING ICONS
if ((ei.title.contains("Sync Successful")) {
    imageicon.setImageResource(R.drawable.ok);
}
else {
    imageicon.setImageResource(R.drawable.wrong);
}

答案 1 :(得分:0)

首先,当你有大量的列表项时,你的适配器将会延迟,你应该使用ViewHolder模式,如HERE所述

其次,最好从sharedPreferences获取所有数据并将它们存储在ArrayList中并将该列表提供给适配器,读取和写入SharedPreferences是一项广泛的操作。 如果同步成功或失败,还要在Item对象中使用布尔值,并在适配器中使用布尔值,这样就更改了列表项的drawable。