我正在从PreferenceActivity迁移到PreferenceFragment(v14),当我尝试点击EditTextPreference时,应用崩溃。 该代码与PreferenceActivity一起使用,这就是为什么我不太明白为什么会引发NullPointerException的原因。
这是代码的重要部分:
private Preference websitePref;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
websitePref = findPreference(getString(R.string.preference_key));
websitePref.setIconSpaceReserved(false);
final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
final String savedWebsite = sharedPrefs.getString(websitePref.getKey(), "");
websitePref.setSummary(savedWebsite);
...
我尝试将Preference更改为EditTextPreference并进行转换,但仍然出现相同的错误:
10-05 13:55:36.694 22397-22397/de.test.browserelement E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.test.browserelement, PID: 22397
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.EditText.requestFocus()' on a null object reference
at android.support.v14.preference.EditTextPreferenceDialogFragment.onBindDialogView(EditTextPreferenceDialogFragment.java:66)
at android.support.v14.preference.PreferenceDialogFragment.onCreateDialog(PreferenceDialogFragment.java:149)
at android.app.DialogFragment.onGetLayoutInflater(DialogFragment.java:410)
at android.app.Fragment.performGetLayoutInflater(Fragment.java:1435)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2422)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2201)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2155)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2056)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
这是我的preferences.xml中的EditTextPreference:
<EditTextPreference
android:defaultValue="@string/preference_default"
android:key="@string/preference_key"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/preference_title"
android:dependency="@string/sperr_key"
android:inputType="textVisiblePassword" />
答案 0 :(得分:0)
我有同样的问题。由于某些原因,它默认情况下不会设置对话框的布局。
尝试将其强制转换为EditTextPreference并添加以下代码行: websitePref.setDialogLayoutResource(R.layout.preference_dialog_edittext);