android - 在 PreferenceActivity 中找不到自定义首选项的首选项

标签 android android-preferences preferenceactivity

我制作了一个自定义首选项布局,每行有 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/

相关文章:

android - 我们是否需要在 cocos2dx 中使用 Sprite 作为 2 的幂

android - 以编程方式安装位于/res/raw 中的 .apk 文件

java - 如何检查用户是否第一次使用我的应用程序

android - 无法注册 BroadcastReceiver

java - 在没有 Google Cloud 的情况下同步 Android 设备

java - Android 将 Int 转换为 Hex 颜色

android - 首选项支持库 - SwitchPreference 不起作用

java - 通过java代码初始化EditTextPreference的defaultValue

android - 无法启动我的偏好 Activity

android - 设置首选项布局并更改其中的属性