如何在我的首选项片段中添加一个监听器?

时间:2015-11-10 17:09:44

标签: android android-fragments listeners preferencefragment

我需要将onPreferenceChangeListener设置为我的首选项片段,但我不知道我该怎么办...这是我的代码

public class PrefsFragment extends PreferenceFragment {
    Context context;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        context = this.getActivity();
        context.setTheme(R.style.myStyle);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        view.setBackgroundColor(0x96000000);
        return view;
    }
}

1 个答案:

答案 0 :(得分:2)

您的PrefsFragment需要实现OnSharedPreferenceChangeListener接口,例如:

public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {...

然后,您可以实现onSharedPreferenceChanged方法:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
    //do something 
}

}

确保您也注册了听众:

@Override
public void onResume() {
    super.onResume();
    getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

}

@Override
public void onPause() {
    getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    super.onPause();
}