How to fill ListPreference dynamically when onPreferenceClick is triggered?

前端 未结 3 1832
庸人自扰
庸人自扰 2020-12-13 09:55

I have a preference activity that has a language as ListPreference which displays the available language list. I can fill the list when onCreate is

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 10:15

    I solved the problem my extending the ListPreference. It was very simple.

    public class DListPref extends ListPreference
    {
        public interface LoadingListener
        {
            void setData(ListPreference lp);
        }
    
        LoadingListener TheLL;
    
        public void setLoadingListener(LoadingListener l)
        {
            TheLL = l;
        }
    
        @Override
        protected void onPrepareDialogBuilder(AlertDialog.Builder builder)
        {
            if(TheLL!=null)
            {
                TheLL.setData(this);
            }
            super.onPrepareDialogBuilder(builder);
        }
    
        //Do not mind the rest of this class, as they are auto-generated boilerplate code.
        public DListPref(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
        {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        public DListPref(Context context, AttributeSet attrs, int defStyleAttr)
        {
            super(context, attrs, defStyleAttr);
        }
    
        public DListPref(Context context, AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        public DListPref(Context context)
        {
            super(context);
        }
    }
    

    And then I just changed the name to my class in the XML.

    
    

    And then I simply did this at the onCreate.

            DListPref lp = (DListPref) findPreference("damn");
    
            lp.setLoadingListener(new DListPref.LoadingListener()
            {
                @Override
                public void setData(ListPreference lp)
                {
                    lp.setEntries(new String[]{"doge", "wow"});
                    lp.setEntryValues(new String[] {"1", "2"});
                    lp.setDefaultValue("1");
                }
            });
    

    Worked right away. Actually, I never expected it would be done so easily.

提交回复
热议问题