【问题标题】:How to set Icons into ListItems dynamically?如何动态地将图标设置为 ListItems?
【发布时间】:2013-11-25 09:55:55
【问题描述】:

我有一个 ListView,其列表项来自 Shared Preference 中的“String”。现在我必须设置两个图标“成功”和“失败”,从字符串中识别那些关键字“成功”和“失败”。但是在设置时,要么为所有列表项设置“成功”图标,要么为所有原因设置“失败”图标,因为字符串包含两者。知道如何识别每个列表项并为它们设置图标吗?以下是我的代码:

我从共享首选项中检索“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);
    }




}

问候

【问题讨论】:

    标签: android listview sharedpreferences


    【解决方案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);
    }
    

    【讨论】:

    • 非常感谢 Amulya...这确实有效。我多么愚蠢...我从共享首选项中获取字符串值并试图从中识别...上帝保佑你
    【解决方案2】:

    首先,当您有大量列表项时,您的适配器会滞后,您应该使用 HERE 中描述的 ViewHolder 模式

    其次,最好从 sharedPreferences 中获取所有数据并将它们存储在 ArrayList 中并将该列表提供给适配器,读取和写入 SharedPreferences 是一个扩展操作。 还要处理同步是成功还是失败,请在您的 Item 对象中使用布尔值,并在适配器中检查该布尔值并像这样更改列表项的可绘制对象。

    【讨论】:

    • 谢谢@Eddy,但这对我来说代价高昂,因为我必须做出很多改变
    • 这将使您以后的生活更轻松,当您添加更多您想要显示的内容时,或者事件添加另一个检查选项以显示成功或失败,顺便检查一个字符串。 equalsignoreccase 或 contains 也是很繁重的操作
    • 我同意,我迟早要做出改变... :(
    • 是的,最好从头开始做,只是在代码中添加选项而不是重写:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多