我使用的是自定義佈局從一個偏好:自定義佈局在首選項使NullPointerException異常
<PreferenceCategory
android:title="Intolleranze">
<Preference android:layout="@layout/intolerance_settings" />
</PreferenceCategory>
佈局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editTextIntolerance"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Aggiungi intolleranza..." />
<Button
android:id="@+id/addIntoleranceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:background="@drawable/oval_button"
android:text="@string/add"
android:textColor="@android:color/white"
style="?android:attr/borderlessButtonStyle"/>
</LinearLayout>
當我嘗試從首片段,我得到添加一個onClick監聽器NullPointerException,因爲我無法獲得對PreferenceScreen中設置的自定義佈局的引用。我該如何解決這個問題?
PreferenceFragment:
public class SettingsFragment extends PreferenceFragment {
private Set<String> set;
private Set<String> in;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
getActivity().setTitle("Impostazioni");
return view;
}
@Override
public void onViewCreated(View view, Bundle savedIstanceState){
Button addBtn = (Button) findViewById(R.id.addIntoleranceButton);
final EditText editText = (EditText) findViewById(R.id.editTextIntolerance);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//NullPointerException
}
});
}
我知道一個NullPointerException是什麼。我在這個特殊情況下要問如何避免它。 –
發佈您的完整PreferenceFragment類代碼 – FAT
我已經發布了整個片段 –