У меня есть предпочтение Фрагмент, где я вызываю setOnClickListener()
для предпочтения и переопределяю метод onPreferenceClick()
. Тем не менее, мой новый метод не вызывается при нажатии кнопки предпочтения.Android OnPreferenceClick не вызывается при нажатии
Я мог бы получить ClickListener
, переместив код на свой собственный класс EditTextPreference
, но предпочтение должно было быть включено для запуска слушателя.
Я хочу использовать это предпочтение как ярлык для отображения значения, и при нажатии на него отображаются параметры, чтобы изменить его. Я не хочу, чтобы пользователь редактировал его напрямую.
Как я могу достичь этого.?
код, как показано ниже
public class PrefActivity extends PreferenceActivity {
static final String TAG="Preference Activity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference clickedPreference = (Preference) findPreference("userLocation");
clickedPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
boolean locationTypeSetting;
LocationSetting locationSetting = new LocationSetting(preference.getContext());
String clickedPreference = preference.getKey();
if (clickedPreference.equals("userLocation")){
locationTypeSetting = settings.getBoolean("locationSetting", false);
if (locationTypeSetting == true)
{
AlertDialog.Builder noEditDialogBuilder = new AlertDialog.Builder(preference.getContext());
noEditDialogBuilder.setTitle(R.string.no_edit_dialog_title);
noEditDialogBuilder
.setMessage(R.string.no_edit_dialog_message)
.setPositiveButton(R.string.no_edit_dialog_positive_action,null);
AlertDialog noEditDialog = noEditDialogBuilder.create();
noEditDialog.show();
}
else
locationSetting.displayMap(0);
}
return false;
}
});
}
}
}
Мой Preference XML
<SwitchPreference
android:defaultValue="0"
android:key="locationSetting"
android:summary="Automatic Location"
android:switchTextOff="OFF"
android:switchTextOn="ON" />
<com.example.test.EditTextPreferenceWithSummary
android:key="userLocation"
android:title="Address"
android:shouldDisableView="false"
android:enabled="false"
android:selectable="true" />
Мой EditTextPreferenceWithSummary класс
public class EditTextPreferenceWithSummary extends EditTextPreference {
private final static String TAG = EditTextPreferenceWithSummary.class.getName();
@Override
protected View onCreateView(ViewGroup parent) {
this.setSummary(this.getText());
return super.onCreateView(parent);
}
public EditTextPreferenceWithSummary(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EditTextPreferenceWithSummary(Context context) {
super(context);
init();
}
private void init() {
Log.e(TAG, "init");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getContext());
String currentText = prefs.getString("userLocation", this.getText());
this.setSummary(currentText);
setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
}
}
Я удалил фрагмент и непосредственно использовал класс. Все та же проблема
код, как показано ниже
public class PrefActivity extends PreferenceActivity {
static final String TAG="Preference Activity";
@SuppressWarnings("deprecation")
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference clickedPreference = (Preference) findPreference("userLocation");
clickedPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
boolean locationTypeSetting;
LocationSetting locationSetting = new LocationSetting(preference.getContext());
String clickedPreference = preference.getKey();
if (clickedPreference == "userLocation"){
locationTypeSetting = settings.getBoolean("locationSetting", false);
if (locationTypeSetting == true)
{
AlertDialog.Builder noEditDialogBuilder = new AlertDialog.Builder(preference.getContext());
noEditDialogBuilder.setTitle(R.string.no_edit_dialog_title);
noEditDialogBuilder
.setMessage(R.string.no_edit_dialog_message)
.setPositiveButton(R.string.no_edit_dialog_positive_action,null);
AlertDialog noEditDialog = noEditDialogBuilder.create();
noEditDialog.show();
}
else
locationSetting.displayMap(0);
}
return false;
}
});
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
}
Помечен как неконструктивная, потому что, если вы не имеете проблему, вы должны смотреть на [ссылка для Android] (http://developer.android.com/reference/android/preference/PreferenceFragment.html) – verybadalloc
У меня проблема, и поэтому я задал вопрос. Я не понимаю этот комментарий. – user2516536
Добро пожаловать в переполнение стека. К сожалению, вы не предоставили достаточно информации, чтобы мы могли вам помочь. Пожалуйста, прочитайте [эти предложения] (http://stackoverflow.com/help/how-to-ask), чтобы улучшить свой вопрос. Чем больше усилий вы ставите в вопросе хорошего вопроса, тем более вероятно, что кто-то предоставит ответы, которые вы ищете. –