0

I am learning how to set up preferences in an android application. I have a file res/xml/prefs.xml with a few different component(?) things in it. This is referenced by Prefs.java, which uses addPreferencesFromResource(R.xml.prefs); in its onCreate() method. As I understand, the prefs.xml file sets up the preferences, and the Prefs.java file accesses the prefs.xml to give it logic (that I would then program).
Then in my Manifest, I have one of the activities as

<activity
    android:name=".Prefs"
    android:label="Preferences" >
    <intent-filter>
        <action android:name="com.example.lesson1.PREFS" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Not really sure if Manifest references Prefs.java or if it's the other way around or what.
In addition (the most confusing right now), I have another file called Splash.java, which displays a splash screen. On the splash screen's onCreate(), it does this:

    MediaPlayer ourSong = MediaPlayer.create(Splash.this, R.raw.splash);
    SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext()); 
    boolean music = getPrefs.getBoolean("checkbox", true);
    if (music) {
        ourSong.start();
    }

I'm not really sure how this knows where the preferences (any one of them, or whichever one it references to) are. I never told it that prefs.xml is the preferences file, or where it is. So is this a default that the preferences are in res/xml/prefs.xml and it knows that automatically?
I'm just really confused aboout the whole order of things. Which file references which? How does the manifest come into play here (it seems like it just points to the .java file to tell the android app that it's there, but i don't really know). And finally, is it possible to state that the preferences are in a different .java and .xml file, or do they have to be called prefs.java/.xml?
Thanks, sorry if this is confusing. I'm pretty confused myself and can't really tell if I'm making sense completely here.

4

1 に答える 1

0

アプリをコンパイルすると、resフォルダー内のさまざまなものがコンパイルされます。この場合、xmlフォルダーはrawフォルダーとして認識さR.xml.prefsれ、自動生成されたコードに追加されます。

実行時に、これはrawリソースとして扱われ、データが読み込まれます(実際には、レイアウトインフレーターの動作と同様に、インフレーターを使用して構築されます)。実際にデータを自分で見ることができます...

InputStream is = context.getResources().openRawResource(R.xml.prefs);

したがって、実行時にaddPreferencesFromResource(R.xml.prefs)、設定をロードするのに十分です。

プリファレンスへのアクセスに関しては、プリファレンスはSharedPreferencesに保存されます。「チェックボックス」と呼ばれる設定があると仮定します。呼び出したときにgetPrefs.getBoolean("checkbox", true)、そのSharedPreference値が見つからない場合(設定がまだ設定されていないため)、それが返されますtrue(2番目の引数)。

これが、デフォルトで一貫していることが非常に重要である理由です。異なる場所で誤って異なる値にデフォルト設定されないように、設定とのインターフェース専用のクラスを用意することは、実際にはおそらく価値があります。

resフォルダーには多くの自動生成の魔法があります。たとえば、誰もres/values/strings.xmlが文字列を保存するために使用しますが、実際にはファイル名が何であるかは関係ありません。のすべてが読み取らres/values/れてマージされ、各ファイルはあらゆる種類のデータ型(文字列、整数、色など)の混合物にすることができます。

于 2012-07-12T04:30:14.530 に答える