Android:如何在自定义首选项(布局)中使用非默认共享首选项(数据)

时间:2017-05-21 18:10:13

标签: android android-preferences android-sharedpreferences

对于这个机会,我需要使用非默认(即自定义)共享偏好数据。如何在自定义首选项布局中访问此自定义共享首选项数据?在这种情况下,我不能使用getDefaultSharedPreferences(context);

我构建了一个自定义列表首选项,允许向其中添加新元素。 我不得不使用Android 4.这个问题不是很重要。

简单的MainActivity只显示首选项列表,只有一个自定义首选项布局。

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();
        }
    }
}

res / 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。

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;
            }
        }
    }
}

在arrays.xml中,“@ array / 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>

2 个答案:

答案 0 :(得分:1)

要检索非默认SharedPreference,您需要致电getSharedPreferences

答案 1 :(得分:0)

@ X3Btel,谢谢你给我指路。

自定义ListPreferenceExpandable应该多次重复使用。旧应用程序为每个不同的目标组使用单独的SharedPreference。

那么我怎样才能将SharedPreference的名称传递给自定义ListPreference?

最简单的方法是为每个目标组创建一个单独的preference.xml文件。在每个preference_targetgroup_n.xml中,我输入了该目标组的sharedPreference的名称。

preference_targetgropu_n.xml:

printRepeating

为了使我的ListPreference可以在这种情况下重复使用,我输入了自定义首选项:

<nl.xyz.listpreferenceexpandable.ListPreferenceExpandable
        android:key="custom3"
        android:title="CustomList3"
        android:dialogTitle="Add custom item"
        android:entries="@array/customdata1"
****    sharedPreference="sharedpreferences_of_targetgroup_n" ****
        android:entryValues="@array/customdata1"/>