我制作了一个自定义首选项布局,每行有 2 个开关,称为 dualtogglepreference。连同一个扩展 Preference 的类,该类处理它的一些细节。当我将此自定义首选项添加到我的 preferences.xml 文件时,它出现在 UI 中,但我无法在首选项 Activity 中使用 findPreference 来引用它。
preferences.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Notifications">
<com.hitpost.testing.DualTogglePreference
android:key="followsMe"
android:title="Someone follows me"
android:layout="@layout/dualtogglepreference"/>
</PreferenceCategory>
</PreferenceScreen>
偏好 Activity
public class TestingCustomPreferenceActivity extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
DualTogglePreference followsMe = (DualTogglePreference) findPreference("followsMe");
if (followsMe != null)
Log.e("FOLLOWS_ME", "NOT NULL");
else
Log.e("FOLLOWS_ME", "NULL"); //THIS IS PRINTED
}
}
视觉上一切看起来都很完美,即小部件的布局是正确的。请帮忙,最后一天一直在与此作斗争。
最佳答案
在我的例子中,我忽略了定义将由充气机使用的构造函数。
public class StaticDialogPreference extends DialogPreference {
// this constructor is called by the infaltor
public StaticDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public StaticDialogPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setDialogMessage(getContext().getString(R.string.static_message));
setNegativeButtonText(null);
}
}
关于android - 在 PreferenceActivity 中找不到自定义首选项的首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717895/