【问题标题】:Android use findViewById in PreferenceFragment gives NullPointerExceptionAndroid 在 PreferenceFragment 中使用 findViewById 会给出 NullPointerException
【发布时间】:2021-06-10 18:35:07
【问题描述】:

我有一个包含自定义布局的首选项屏幕:

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<Preference
    android:key="myKey"
    android:layout="@layout/my_layout" />


<ListPreference
    app:defaultValue="@string/defaultGender"
    app:entries="@array/gender_entries"
    app:entryValues="@array/gender_values"
    app:key="gender"
    app:title="@string/gender"
    app:useSimpleSummaryProvider="true" />

我正在尝试在 my_layout 中设置 TextView 的值:

public static class MyFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preference_screen, rootKey);
        TextView textView= (TextView) this.getActivity().findViewById(R.id.myTextView);
        textView.setText("XXX");
    }

}

但我在textView.setText("XXX"); 上收到NullPointerException

我做错了什么?

【问题讨论】:

    标签: android android-fragments nullpointerexception android-preferences


    【解决方案1】:

    尝试在 onViewCreated 函数中设置文本。

    @Override
    public void onViewCreated (View view, Bundle savedInstanceState) {
        TextView textView= (TextView) this.getActivity().findViewById(R.id.myTextView);
        textView.setText("XXX");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      相关资源
      最近更新 更多