在PreferenceActivity中找不到自定义偏好设置的findPreference。

3
我已经创建了一个自定义的偏好设置布局,每行有两个开关,称为dualtogglepreference。还有一个扩展Preference类的类来处理其中的一些细节。当我将这个自定义偏好设置添加到我的preferences.xml文件中时,它会出现在用户界面中,但我无法在Preference Activity中使用findPreference引用它。
<?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>

偏好设置活动(PreferenceActivity)
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
}
}

从视觉上看,一切都很完美,即小部件的布局是正确的。请帮忙,我已经为此奋斗了一整天。


你是否得到了 followsMe 为 NULL 的值?我无法确切地找出你所遇到的问题。请提供更多信息。 - kosa
是的,followsMe 出现了 null。 - Leo
希望你使用了 DualTogglePreference 扩展 Preference。如果还没有,可以参考这个链接:http://www.java2s.com/Code/Android/Core-Class/AcustompreferencetypeThepreferencecountsthenumberofclicksithasreceivedandstoresretrievesitfromthestorage.htm - kosa
是的,DualTogglePreference扩展了Preference。虽然我没有按照那个链接使用所有的方法。 - Leo
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/6362/discussion-between-leo-and-thinksteep - Leo
显示剩余3条评论
1个回答

2
在我的情况下,我忽略了定义由inflator使用的构造函数。
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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接