Domanda

From the sameple custom row in a listPreference? i tried to create my own custom listpreference but nothing is getting saved or doesn't get populate old indexes.

 public class FontSizePreference extends ListPreference {
    private CustomListPreferenceAdapter customListPreferenceAdapter = null;

    private Context mContext;

    private LayoutInflater mInflater;

    // private CharSequence[] entries;

    // private CharSequence[] entryValues;

    private ArrayList<RadioButton> rButtonList;

    private SharedPreferences prefs;

    private SharedPreferences.Editor editor;

    private static final String TAG = FontSizePreference.class.getSimpleName();

    private String font_size = "";

    public FontSizePreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mInflater = LayoutInflater.from(context);
        rButtonList = new ArrayList<RadioButton>();
        prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        editor = prefs.edit();
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {

        font_size = prefs.getString(KEY_FONT_SIZE, "18");

        if (getEntries() == null || getEntryValues() == null
                || getEntries().length != getEntryValues().length) {
            throw new IllegalStateException(
                    "ListPreference requires an entries array and an entryValues array which are both the same length");
        }

        customListPreferenceAdapter = new CustomListPreferenceAdapter(mContext, getEntries(),
                getEntryValues());

        builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        super.onPrepareDialogBuilder(builder);
    }

    private class CustomListPreferenceAdapter extends BaseAdapter {

        private CharSequence[] entries;

        private CharSequence[] entryValues;

        public CustomListPreferenceAdapter(Context mContext, CharSequence[] entries,
                CharSequence[] entryValues) {
            this.entries = entries;
            this.entryValues = entryValues;
        }

        public int getCount() {
            return entries.length;
        }

        public Object getItem(int position) {
            return entries[position];
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            CustomHolder holder = null;
            View row = convertView;
            if (row == null) {
                row = mInflater.inflate(R.layout.fontsize_layout, parent, false);
            }
            boolean flag = false;
            for (CharSequence entry : entryValues) {
                if (entry.toString().equals(font_size)) {
                    flag = true;

                }
            }
            holder = new CustomHolder(row, position, font_size, flag);
            row.setTag(holder);
            row.setClickable(false);
            row.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    for (RadioButton rb : rButtonList) {
                        Log.d(TAG, "current row listener : " + rb.getId() + " : : : " + position);

                        if (rb.getId() != position)
                            rb.setChecked(false);
                        else
                            rb.setChecked(true);
                    }

                    int index = position;
                    String value = (String)entryValues[index];
                    editor.putString(KEY_FONT_SIZE, value).commit();
                    getDialog().dismiss();
                }
            });

            return row;
        }

        class CustomHolder {
            private TextView text = null;

            private RadioButton rButton = null;

            CustomHolder(final View row, final int position, String prefValue, boolean checked) {

                Log.d(TAG, "current position is : " + position);
                text = (TextView)row.findViewById(R.id.fontSizeTitle);
                text.setText(entries[position]);
                text.setTextSize(Float.valueOf(entryValues[position].toString()));

                rButton = (RadioButton)row.findViewById(R.id.fontSizeState);
                int newIndex = Arrays.asList(entryValues).indexOf(prefValue);
                // rButton.setId(newIndex);
                if (position != newIndex)
                    rButton.setChecked(false);
                rButtonList.add(rButton);

                rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // TODO Auto-generated method stub
                        if (isChecked) {
                            for (RadioButton rb : rButtonList) {
                                if (rb != buttonView)
                                    rb.setChecked(false);
                                else {
                                    rb.setChecked(true);
                                }

                            }
                        }

                        int index = buttonView.getId();
                        String value = (String)entryValues[position];

                        editor.putString(KEY_FONT_SIZE, value).commit();

                        getDialog().dismiss();
                    }
                });
            }
        }
    }

everytime i run this sample it generates 35 instances of radio buttons and it doesn't show either the previous selected button or currently selected button in the view. Please help me in fixing this issue. Here are xml code for arrays,layout and prefernce call

<string-array name="font_size_options">
        <item>Larger</item>
        <item>Large</item>
        <item>Medium</item>
        <item>Small</item>
        <item>Smallest</item>
    </string-array>

    <string-array name="font_size_values">
        <item>26</item>
        <item>20</item>
        <item>18</item>
        <item>14</item>
        <item>10</item>
    </string-array>

layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:id="@+id/fontSizeTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"

        />



    <RadioButton
        android:id="@+id/fontSizeState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0" />

</LinearLayout>

and preference is :

<com.example.samplepreference.FontSizePreference
            android:key="semc_pref_key_font_size"
            android:entries="@array/font_size_options"
            android:entryValues="@array/font_size_values"
            android:title="@string/font_size_title" />

also setting button (rButton.setId(newIndex)) always return nullpointer.

È stato utile?

Soluzione

I fixed this with another approach from another example (picked idea) forgot the link to that solution but will update it once i found it.

public class FontSizePreference extends ListPreference {

    private Context mContext;

     private CharSequence[] entries = null;

     private CharSequence[] entryValues = null;

    private SharedPreferences prefs;

    private SharedPreferences.Editor editor;

    private static final String TAG = FontSizePreference.class.getSimpleName();

    private String font_size = "";

    public FontSizePreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        editor = prefs.edit();
        entries = getEntries();
        entryValues = getEntryValues();

    }



    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return super.onGetDefaultValue(a, 2);
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {

        String choosenIndex = getPersistedString("18");
        choosenIndex = (!getValue().equals(choosenIndex)) ? choosenIndex : getValue();
        ListAdapter adapter = new FontSizeListAdapter(getContext(),
                R.layout.fontsize_layout, entries, entryValues,
                Arrays.asList(entryValues).indexOf(choosenIndex) ,this);
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });
        super.onPrepareDialogBuilder(builder);
    }

 class CustomListAdapter implements ListAdapter {

        private int selectedIndex = 0;

        public CustomListAdapter(Context context, int customFontLayout,
                CharSequence[] entries, CharSequence[] entryValues,
                int selectedValue) {
            this.selectedIndex = selectedValue;
        }

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

        @Override
        public Object getItem(int index) {
            return entryValues[index];
        }

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

        @Override
        public int getItemViewType(int index) {
            return index;
        }

        @Override
        public View getView(final int index, View anotherView, ViewGroup parent) {

           View row = anotherView;

            if (row == null) {
                row = LayoutInflater.from(getContext()).inflate(
                        R.layout.fontsize_layout, parent, false);
            }
            TextView txtView = (TextView) row.findViewById(R.id.fontSizeTitle);
            RadioButton buttonView = (RadioButton) row
                    .findViewById(R.id.fontSizeState);
            row.setId(Integer.valueOf(entryValues[index].toString()));
            txtView.setText(entries[index]);

            if (index == selectedIndex) {
                buttonView.setChecked(true);
            }
            txtView.setTextSize(Float.valueOf((String) entryValues[index]));
            row.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    persistString(String.valueOf(v.getId()));

                    getDialog().dismiss();
                }
            });

            buttonView.setOnCheckedChangeListener(
                  new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean isChecked) {

                            if (isChecked) {
                                buttonView.setId(index);
                                persistString(
                                String.valueOf(entryValues[buttonView.getId()]));
                                getDialog().dismiss();
                            }

                        }
                    });

            return row;
        }

        @Override
        public int getViewTypeCount() {
            // TODO Auto-generated method stub
            return entryValues.length;
        }

        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void registerDataSetObserver(DataSetObserver arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void unregisterDataSetObserver(DataSetObserver arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean areAllItemsEnabled() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isEnabled(int arg0) {
            // TODO Auto-generated method stub
            return false;
        }

    }

    @Override
    protected String getPersistedString(String defaultReturnValue) {
        return super.getPersistedString(defaultReturnValue);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        if (!restoreValue) {
            super.onSetInitialValue(restoreValue,"18");
        } else
            super.onSetInitialValue(restoreValue, defaultValue);
    }

    public boolean persistString (String value) {
        return super.persistString(value);
    }



}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top