how to programatically modify a CheckBoxPreference view

回眸只為那壹抹淺笑 提交于 2019-12-12 02:25:31

问题


How can I change the view of a CheckBoxPreference at runtime?

Specifically, I'd like to change a CheckBoxPreference summary depending on whether the user has checked the box or not.

If it were a normal view, I could do something like:

view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");

But a CheckBoxPreference has no id, so I don't know how to get a "handle" to it.


回答1:


I have an answer to my own question. The key is to use findPreference in a PreferenceActivity, as follows:

public class MyPreferenceActivity extends PreferenceActivity{

    private SharedPreferences preferences;
    private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
    private CheckBoxPreference pref;

    @Override    
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        pref = (CheckBoxPreference) findPreference(res.getString(R.string.keyAccount));
        pref.setSummary("something");

        //-- preference change listener
        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
             public void onSharedPreferenceChanged(SharedPreferences prefs, String key){  
                 if (key.equals(somekey)){                                       
                     pref.setSummary("something new");

                 }
             }
        };
        preferences.registerOnSharedPreferenceChangeListener(prefListener);     
    }

This is tested and works.




回答2:


You should use (in XML layout file):

android:summaryOff
android:summaryOn



回答3:


You can set id to CheckBoxPreference using android:id in xml like code below

<CheckBoxPreference
        android:key="pref_boot_startup"
        android:title="Auto start"
        android:defaultValue="true"
        android:id="@+id/my_CheckBoxPref"
        />

To retrieve you can use

CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);


来源:https://stackoverflow.com/questions/8656203/how-to-programatically-modify-a-checkboxpreference-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!