如何将首选项与活动连接?

时间:2017-04-23 14:08:59

标签: java android android-studio

对于Android Studio来说很新,我在连接CheckBoxs时遇到问题'在我的preferences.xml中包含我的所有其他活动,因此它们充当应用程序的设置。我已经设置了所有内容,就像官方页面(https://developer.android.com/guide/topics/ui/settings.html)所说的那样,但我仍然无法让一切正常运作。

这是我的设置类:

public class Settings extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }
}

和我的SettingsFragment类:

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
     }
}

我尝试做的是在检查时切换音乐或sfx,如果在应用程序周围取消选中则关闭,这是我的偏好.xml:

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

    <CheckBoxPreference
        android:key="music check box"
        android:title="Music"
        android:defaultValue="true"
        android:id="@+id/checkMusic"/>

    <CheckBoxPreference
        android:key="sfx check box"
        android:title="SFX"
        android:defaultValue="true"
        android:id="@+id/checkSfx"/>

    <CheckBoxPreference
        android:key="notifications check box"
        android:title="Notifications"
        android:defaultValue="true"
        android:id="@+id/checkNotif"/>

</PreferenceScreen>

现在我的MediaPlayer位于Application类中,因此它可以绕过每个活动。我如何解决所有这些问题?

1 个答案:

答案 0 :(得分:0)

  

现在,我的MediaPlayer位于Application类中,因此它可以解决每个活动

这可能不是正确的模式。

  

我如何解决所有这些问题?

让组件管理您的MediaPlayerApplication,可能是Service以后的某个时间)registerOnSharedPreferenceChangeListener()上的SharedPreferences,以了解相关信息变化。然后,根据需要对这些变化做出反应。