【发布时间】:2015-12-31 15:58:54
【问题描述】:
我尝试制作自定义首选项布局,因为我想用它制作颜色选择器。
我使用了here的解决方案:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFragment()).commit();
}
我想在布局上编辑 TextView 的值,这就是为什么我在其中添加带有 TextView 的行。
问题是它在 setText 行上抛出了 NullPointerException,因为我认为 findViewById() 方法返回了 null。
PrefFragment.java:
public class PrefFragment extends PreferenceFragment {
private TextView titleTV;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
titleTV = (TextView) getActivity().findViewById(R.id.title);
titleTV.setText(R.string.pref_bgcolor);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="@string/pref_bgcolor"
android:summary="@string/pref_bgcolor_sum"
android:key="hu.atsoft.myip.color"
android:widgetLayout="@layout/color_pref"/>
</PreferenceScreen>
color_pref.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/color_preference">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:paddingTop="5dip"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip"
android:layout_alignParentLeft="true"
android:layout_below="@id/title"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<ImageView
android:id="@+id/color_preview"
android:layout_width="20dip"
android:layout_height="20dip"
android:background="@android:color/darker_gray"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="5dip"/>
</RelativeLayout>
我应该使用什么来访问元素而不是 findViewById() 方法?
【问题讨论】:
-
从哪里获得 PrefFragment?
-
将 findviewbyId 移到 PrefFragment 中的 onActivityCreated 中。
-
它仍然在 setText() 行上抛出相同的 NullPointerException。
-
我从来没有使用过 PreferenceFragment。我从其他地方复制了一些东西。我更喜欢自己创建整个片段。
标签: android preferences