gpt4 book ai didi

android - 无法从 preferencefragment 获取 View

转载 作者:行者123 更新时间:2023-11-29 01:44:01 29 4
gpt4 key购买 nike

我有以下首选项 fragment xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<PreferenceScreen
android:order="1"
android:summary="Sound settings"
android:title="Sound"
android:widgetLayout="@layout/preference_switch_sound" >
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.test.SoundPreferencesActivity"
android:targetPackage="com.test" />
</PreferenceScreen>

</PreferenceScreen>

还有我在上面指向的声音开关 widgetLayout:

<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/soundSwitchWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="16dip"
android:focusable="false"
android:clickable="true" />

我的问题是我需要在代码中获取开关以便我可以附加 onClickListener。

我尝试在我的偏好 Activity 中找到 View :

public class PublicPreferencesActivity extends PreferenceActivity {

...

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, preference).commit();
Switch s = (Switch) findViewById(R.id.soundSwitchWidget);
// I always get null here
}

}

我也在我的 fragment 中尝试过:

public static class PublicPreferenceFragment extends PreferenceFragmentSummary  {       
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.publicpreferences);
Switch s = (Switch) findViewById(R.id.soundSwitchWidget);
// switch is null here too

}
}

如何以编程方式访问我在首选项屏幕中放置的开关?

编辑:有一个关于为什么我不使用 SwitchPreference 的问题。基本上我希望能够使用开关打开/关闭声音,但如果他们单击首选项(不是在开关上,而是在标题上),也能够切换到新的 PreferenceScreen。我尝试使用 SwitchPreference,但是当我单击文本时它会切换开关并将我发送到 PreferenceScreen,而不是仅仅将我发送到 PreferenceScreen。

我正在尝试模仿主要设置中的 wifi 行为。 IE。您可以从顶层打开/关闭开关,也可以单击文本以访问更详细的屏幕。

最佳答案

您没有使用 SwitchPreference 的任何特殊原因?

<SwitchPreference
android:order="1"
android:summary="Sound settings"
android:title="Sound" >
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.test.SoundPreferencesActivity"
android:targetPackage="com.test" />
</SwitchPreference>

但就为您的 Switch 调用 View.findViewById 而言,您需要继承 Preference,因为您不能继承PreferenceScreen,然后覆盖 Preference.bindView 并从那里对其进行初始化。

关于android - 无法从 preferencefragment 获取 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587366/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com