2

사용자가 여러 ImageButtons의 소스 이미지를 변경할 수있는 앱을 만들고 있는데, 이것을 SharedPreferences에 저장하고 있습니다. 이미지 가져 오기 및 저장 방법은 다음과 같습니다.SharedPreferences 저축

public int getImage(String item){ 
     SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE); 
     int id = pref.getInt(item, R.drawable.no_item); 
     return id; 
    } 

public void saveImage(String item, int resourceId){ 
     SharedPreferences starterSP = getActivity().getPreferences(Context.MODE_PRIVATE); 
     SharedPreferences.Editor edit = starterSP.edit(); 
     edit.putInt(item, resourceId); 
     edit.apply(); 
    } 

이러한 이미지는 정수로 저장되는 그리기 ID로 저장됩니다.

그러나 드로어 블 폴더에 새 이미지 파일을 추가하고 앱을 다시 실행하면 내 기존 ImageButton 소스가 모두 내 그림 파일 폴더의 다른 이미지로 변경됩니다. 어떻게 이런 일이 일어나지 않도록 할 수 있습니까?

답변

1

drawable ID가 앱이 컴파일 될 때마다 변경되므로 ID 대신 drawable 이름을 저장해야합니다.

당신은 사용 당김 이름으로 드로어 블 리소스 ID를 얻을 수 있습니다 -

final int rsId = getResources().getIdentifier(imageNameFromPreferences, "drawable", 
     context.getPackageName()); 
+0

, imageNameFromPreferences I가 된 SharedPreferences 가치, 그리고 "그릴 수"를 저장하는 데 사용하는 키 (예 : "R.drawable.example"와 같은) 실제 이름이다? –

+0

아니요. 예를 들어'R.drawable.example'에'example' 만 저장해야합니다. 즉,'example'은 당신의'drawable' 이름입니다. – Wizard

0

대신 드로어 블의 이름이 새 드로어 블이 프로젝트에 추가 할 때 변경하고 이름을 사용하지 않기 때문에 아이디의 당김 이름으로 저장을 id를 검색합니다. 만약 내가 제대로 이해하고

public Int getImage(String item) { 
     SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE); 
     String drawable_name = pref.getString(item, null); 
     int id = getResources().getIdentifier(imageNameFromPreferences, drawable_name, 
     context.getPackageName()); 
     return id; 
    } 

public void saveImage(String item, String drawable_name) { 
     SharedPreferences starterSP = getActivity().getPreferences(Context.MODE_PRIVATE); 
     SharedPreferences.Editor edit = starterSP.edit(); 
     edit.putString(item, drawable_name); 
     edit.apply(); 
    }