我正在尝试使偏好响应用户输入,但没有运气。我正在使用PreferenceFragment,似乎到目前为止找不到的任何代码都可以帮助我。
这是我的preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen " >
<PreferenceCategory
"
" >
<CheckBoxPreference
"
"
o aplicativo para uso"
aplicativo" />
</PreferenceCategory>
</PreferenceScreen>
这是我的屏幕代码:
package com.gh0st.gerenciador;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TelaPreferencias extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "prefs_ativar";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()).commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tela_preferencias, menu);
return true;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Toast.makeText(this, "Teste", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
}
我想要的是,当我触摸偏好时,它会显示吐司。该代码似乎很好(没有错误),但是它不起作用。我想我没有听众背后的想法。有人可以帮我吗?
谢谢!
在忘记之前,我正在使用API级别19(Android 4.4)。我不知道这是否会有所改变。
缺少听众的注册?这是我的方法:
// Register the listener
@Override
protected void onResume()
{
// Register OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
registerOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onResume();
}
// Unregister the listener
@Override
protected void onPause()
{
// Unregister OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
unregisterOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onPause();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句