我用這個序列設計的應用程序:集SharedPreferences動態命名
(本類不會改變,我會使用他們的多項活動)
- 定義適配器
- 模型類
- 共享偏好
而且Activity
與標籤佈局(具有兩個星期五擴大)至極包含:
我會名稱是:(包#1)
- MainActivity
- 片段的一種
- 片段二
現在我想複製軟件包#1並更改一些內容,然後將其命名爲軟件包#2。但我在這裏遇到問題。
我對包#1,包#2,包#3使用了一個共享首選項,對吧? 請看看到我的共享偏好類:
public class SharedPreference_light {
private SharedPreferences settings;
private SharedPreferences.Editor editor;
private Gson gson = new Gson();
private static final String PREFS_NAME = "Light_Products";
private static final String FAVORITES = "Favorite_Tones_Light";
public SharedPreference_light(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
private void saveFavorites(List<ProductLocal> favorites) {
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
public void addFavorite(ProductLocal product) {
List <ProductLocal> favorites = getFavorites();
if (favorites == null)
favorites = new ArrayList<>();
favorites.add(product);
saveFavorites(favorites);
}
public void removeFavorite(ProductLocal product) {
ArrayList <ProductLocal> favorites = getFavorites();
if (favorites != null) {
favorites.remove(product);
saveFavorites(favorites);
}
}
public ArrayList <ProductLocal> getFavorites() {
List<ProductLocal> favorites;
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
ProductLocal[] favoriteItems = gson.fromJson(jsonFavorites, ProductLocal[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList <> (favorites);
} else
return null;
return (ArrayList <ProductLocal>) favorites;
}
}
的問題是,如果我用這個兩個變量:
private static final String PREFS_NAME = "Light_Products";
private static final String FAVORITES = "Favorite_Tones_Light";
會有這些軟件包之間的衝突。因爲我打算將一些列表項添加到共享首選項中並使用getSharedPreferences
。那麼來自多個包的所有這些項目將被添加到一個共享偏好中,而我不想那樣做。現在
我真正的問題是:
如何設置共享偏好名稱(變量)動態?
注: 我有自定義適配器共享偏好的一個用法:
private boolean checkFavoriteItem(ProductLocal checkProduct) {
boolean check = false;
List<ProductLocal> favorites = sharedPreference.getFavorites();
if (favorites != null) {
for (ProductLocal product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
適配器:
public class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.MyViewHolder>{
private SharedPreference_light sharedPreference;
public LocalAdapter(Activity activity, List<ProductLocal> dataList, RelativeLayout snackLayout) {
this.snackLayout=snackLayout;
this.activity = activity;
this.dataList = dataList ;
this.dataListFilter = dataList ;
sharedPreference = new SharedPreference_light(activity);
methods = new Methods(activity);
}
只需將'Name'添加到您的自定義適配器,稍後將該'Name'路由到共享首選項。 – Dusan