이 경우 기본이 아닌 (즉, 맞춤 설정) 공유 우선 설정 데이터를 사용해야합니다. 맞춤 환경 설정 레이아웃에서이 맞춤 공유 환경 설정 데이터에 어떻게 액세스합니까? 이 경우 나는 수 없습니다 사용 getDefaultSharedPreferences (컨텍스트);Android : 맞춤 설정 (레이아웃)에서 기본이 아닌 공유 미리보기 (데이터)를 사용하는 방법
새 요소를 추가 할 수있는 사용자 지정 listpreference를 작성했습니다. Android 4를 사용해야했습니다.이 질문에 대해서는별로 중요하지 않습니다.
간단한 MainActivity는 단지 1 개의 사용자 지정 기본 설정 레이아웃 만있는 기본 설정 목록을 표시합니다.
public class MainActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName("my_preferences");
prefMgr.setSharedPreferencesMode(MODE_PRIVATE);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (Exception e) {
e.printStackTrace();
}
}
}
입술/XML/preferences.xml로 파일에는 다음이 포함
<nl.xyz.listpreferenceexpandable.ListPreferenceExpandable
android:key="custom3"
android:title="CustomList3"
android:dialogTitle="Add custom item"
android:entries="@array/customdata1"
android:entryValues="@array/customdata1"/>
사용자 정의 ListPreference 코드는 다음과 같습니다. 질문 : "my_preferences"라는 이름으로 맞춤 공유 환경 설정 데이터에 액세스하려면 어떻게해야합니까? getPreferenceManager()를 호출하면 null이 반환됩니다.
arrays.xml에서public class ListPreferenceExpandable extends ListPreference {
CustomListPreferenceAdapter customListPreferenceAdapter = null;
Context mContext;
private LayoutInflater mInflater;
List<String> entries;
ArrayList<RadioButton> rButtonList;
SharedPreferences prefs;
SharedPreferences.Editor editor;
String current;
String keyDefault;
String keyData;
public ListPreferenceExpandable(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mInflater = LayoutInflater.from(context);
rButtonList = new ArrayList<RadioButton>();
// THIS IS WRONG:
prefs = PreferenceManager.getDefaultSharedPreferences(context);
// QUESTION: How can I access SharedPreference "my_preferences"
editor = prefs.edit();
keyDefault = getKey();
keyData = getKey() + "_data"; // will hold the dynamically data
String prefDefault = getPersistedString(getKey());
current = prefs.getString(keyDefault, prefDefault);
setSummary(current);
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
getData();
customListPreferenceAdapter = new CustomListPreferenceAdapter(mContext);
builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println("Clicked ... on " + which);
}
});
builder.setNeutralButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
inputDialog("Add new entry");
}
});
}
private void getData() {
String data = prefs.getString(keyData, "");
if(data.isEmpty()) {
entries = new ArrayList<>();
CharSequence[] loadedFromTheResource = getEntries();
if(loadedFromTheResource == null || loadedFromTheResource.length < 1) {
loadedFromTheResource = getEntryValues();
}
if(loadedFromTheResource != null && loadedFromTheResource.length > 0) {
for (CharSequence cs : loadedFromTheResource) {
entries.add(cs.toString());
}
}
} else {
String[] loaded = data.split("\\s*#\\s*");
if(loaded != null && loaded.length > 0) {
entries = Arrays.asList(loaded);
entries = new ArrayList<>(entries);
}
}
if(entries.isEmpty()) {
entries.add(current);
}
}
private void saveData() {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(keyData, TextUtils.join("#", entries));
editor.apply();
}
void inputDialog(String title) {
Builder builder = new Builder(mContext); // this
builder.setTitle(title);
final EditText input = new EditText(mContext); // this
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newEntry = input.getText().toString();
entries.add(newEntry);
customListPreferenceAdapter.notifyDataSetChanged();
saveData();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
static class ViewHolder {
protected TextView nameT = null;
protected TextView formulaT = null;
}
private class CustomListPreferenceAdapter extends BaseAdapter {
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
public CustomListPreferenceAdapter(Context context) { }
public int getCount() {
return entries.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder;
if(convertView == null) {
row = mInflater.inflate(R.layout.custom_list_preference_row, parent, false);
holder = new CustomHolder(row, position);
row.setTag(holder);
} else {
holder = (CustomHolder) row.getTag();
}
holder.row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String current = entries.get(position).toString();
editor.putString(keyDefault, current).apply();
setSummary(current);
Dialog mDialog = getDialog();
mDialog.dismiss();
}
});
String currentSelection = prefs.getString(keyDefault, "");
if(entries.get(position).equals(currentSelection)) {
holder.rButton.setChecked(true);
} else {
holder.rButton.setChecked(false);
}
holder.text.setText(entries.get(position));
return row;
}
class CustomHolder {
private TextView text = null;
private RadioButton rButton = null;
private View row = null;
CustomHolder(View row, int position1) {
text = (TextView)row.findViewById(R.id.custom_list_view_row_text_view);
rButton = (RadioButton)row.findViewById(R.id.custom_list_view_row_radio_button);
this.row = row;
}
public RadioButton getRadioButton() {
return rButton;
}
}
}
}
"@ 배열/customdata1은"그냥 :
<string-array name="customdata1">
<item name="One">One</item>
<item name="Two">Two</item>
</string-array>
행은 다음과 같습니다
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_list_view_row_table_row"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dip"
android:paddingTop="8dip"
android:paddingLeft="10dip"
android:paddingRight="10dip">
<TextView
android:id="@+id/custom_list_view_row_text_view"
android:textSize="22sp"
android:textColor="#000000"
android:gravity="center_vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<RadioButton
android:checked="false"
android:layout_width="40dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:id="@+id/custom_list_view_row_radio_button"/>
</LinearLayout>
하지만이 getSharedPreferences ListPreferenceExpandable에 어떻게 액세스 할 수 있습니까? [1] 나는 시험해 보았습니다 : getPreferenceManager(). getSharedPreferencesName(); 아무것도 표시되지 않습니다. [2] context.getSharedPreferences (getPreferenceManager(). getSharedPreferencesName(), android.content.Context.MODE_PRIVATE)를 사용할 수 없습니다. 아무것도 보이지 않기 때문에. [3] getPreferenceManager()는 null을 제공합니다. – tjm1706
@ tjm1706 context.getSharedPreferences ("my_preferences", MODE_PRIVATE)는 호출해야합니다. 이것이 작동하지 않으면 다른 곳에서 문제가 발생합니다 – X3Btel
예, 알고 있습니다. 문제는 사용자 지정 기본 설정이 다른 설정에서 호출 될 수 있다는 것입니다. 현재 'getSharedPreferencesName'에 따라 사용자 정의 SharedPreference가 사용됩니다. 그래서, 어떻게 내가 현재의 비 기본 SharedPreference 사용자 지정 환경 설정에서 확인할 수 있습니까? – tjm1706