2020-10-26 listview單選儲存

johnzhou_發表於2020-10-26
public class RadioAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private String[] authors;
    private viewHolder holder;
    // 標記使用者當前選擇的那一個作家
    private int index = -1;//預設選擇第一個
    private Context c;
    private SPUtil spUtil;
    public RadioAdapter(Context c, String[] authors, SPUtil spUtil) {
        super();
        this.c = c;
        this.authors = authors;
        inflater = LayoutInflater.from(c);
        this.spUtil = spUtil;
    }

    @Override
    public int getCount() {
        return authors.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        holder = new viewHolder();
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_radio, null);
            holder.nameTxt = (TextView) convertView.findViewById(R.id.author);
            holder.selectBtn = (RadioButton) convertView.findViewById(R.id.radio);
            convertView.setTag(holder);
        } else {
            holder = (viewHolder) convertView.getTag();
        }

        holder.nameTxt.setText(authors[position]);
        holder.selectBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            Log.d("radio", "curr.pos=" + position);
                            index = position;
                            SPUtil.put("new_click", index);
                            notifyDataSetChanged();
                        }
                    }
                });

        int savePos = (int) SPUtil.get("new_click", 0);
        Log.d("radio", "save.pos=" + savePos);

        if (savePos == position) {// 選中的條目和當前的條目是否相等
            holder.selectBtn.setChecked(true);
            Log.d("radio", "is curr index=" + index + ",pos=" + position);
        } else {
            holder.selectBtn.setChecked(false);
            Log.d("radio", "not curr index=" + index + ",pos=" + position);
        }
        return convertView;
    }

    public class viewHolder {
        public TextView nameTxt;
        public RadioButton selectBtn;
    }
}

//MainActivity

private AnimalBaseAdapter adapter;
private SPUtil spUtil;
private ListView radioButtonList;
private RadioAdapter radioAdapter;
// 模擬幾個資料,作為List的條目
private String[] authors = { "芥川龍之介", "三島由紀夫", "川端康成", "村上春樹", "東野圭吾",
        "張愛玲", "金庸"};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spUtil = SPUtil.init(getApplication());

    radioButtonList = (ListView) findViewById(R.id.list);
    radioAdapter = new RadioAdapter(this, authors, spUtil);
    radioButtonList.setAdapter(radioAdapter);

}

 

/**
 * @author : jun
 * @e-mail : johnz0810@163.com
 * @date : 2020/10/24 2:20 PM
 * @desc :
 */


public class SPUtil {

    private static Application app;
    private static volatile SPUtil singleton;
    private static final String APP_ID = "test";


    private SPUtil(Application app) {
        SPUtil.app = app;
    }

    public static SPUtil init(Application app) {
        if (singleton == null) {
            synchronized (SPUtil.class) {
                if (singleton == null) {
                    singleton = new SPUtil(app);
                }
            }
        }
        return singleton;
    }

    /**
     * 儲存資料的方法,拿到資料儲存資料的基本型別,然後根據型別呼叫不同的儲存方法
     *
     * @param key
     * @param obj
     */
    public static void put(String key, Object obj) {
        SharedPreferences sharedPreferences = app.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (obj instanceof String) {
            editor.putString(key, (String) obj);
        } else if (obj instanceof Integer) {
            editor.putInt(key, (Integer) obj);
        } else if (obj instanceof Boolean) {
            editor.putBoolean(key, (Boolean) obj);
        } else if (obj instanceof Float) {
            editor.putFloat(key, (Float) obj);
        } else if (obj instanceof Long) {
            editor.putLong(key, (Long) obj);
        } else {
            editor.putString(key, obj.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }


    /**
     * 獲取儲存資料的方法,我們根據預設值的到儲存的資料的具體型別,然後呼叫相對於的方法獲取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(String key, Object defaultObject) {
        SharedPreferences sharedPreferences = app.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sharedPreferences.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sharedPreferences.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sharedPreferences.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sharedPreferences.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sharedPreferences.getLong(key, (Long) defaultObject);
        } else {
            return sharedPreferences.getString(key, null);
        }
    }


    /**
     * 移除某個key值已經對應的值
     *
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有的資料
     */
    public static void clear(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查詢某個key是否存在
     *
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        return sharedPreferences.contains(key);
    }

    /**
     * 返回所有的鍵值對
     *
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE);
        return sharedPreferences.getAll();
    }


    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查詢apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到則使用apply執行,否則使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}

 

 

相關文章