我有以下首选片段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。
我尝试在我的偏好活动中找到该视图:
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
}
}
我也试过我的片段:
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行为。 I.E.您可以从顶层打开/关闭开关,但也可以单击文本以访问更详细的屏幕。
答案 0 :(得分:2)
您没有使用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>
但就View.findViewById
调用Switch
而言,您需要继承Preference
,因为您不能继承PreferenceScreen
,然后覆盖{{1}并从那里初始化它。
答案 1 :(得分:-1)
onCreate()函数不应该创建任何视图(这对所有类型的片段都是正确的。)
无论需要什么,要访问PreferenceFragment的视图,都必须覆盖onCreateView()。请参阅首选项ListView填充删除示例:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
if (null != view) {
ListView lv = (ListView) view.findViewById(android.R.id.list);
if (null != lv)
lv.setPadding(0, 0, 0, 0);
}
return view;
}