如何获得在 Android 中工作的首选项?

发布于 2024-09-05 00:45:48 字数 4324 浏览 10 评论 0原文

我真的一直在努力解决这个问题。 Java/Android 新手。我正在编写我的第一个应用程序,这是我花了比几天的搜索时间才弄清楚的第一件事。设置如下: 这是一个 BAC 计算器/饮料计数器:

alt text

使用公式来计算 BAC。这是论坛:

Bac = ((StandardDrinks / 2) * (GenderConstant / Weight)) - (0.017 * Hours);

正如您所看到的,能够修改性别和体重将产生更准确和个性化的结果。所以我将它们作为双打:

double GenderConstant = 7.5; //9 for female
double Weight = 180;

为了更改这些变量,我希望人们能够进入设置并选择不同的值。我已经设置了这些东西,但没有链接到上面显示的变量,因为我无法弄清楚如何设置。它们是:

alt text

我按下菜单按钮,然后弹出。伟大的。我将单击“设置”。

alt text

现在会弹出首选项。这是我的preferences.xml:

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

 <PreferenceCategory android:title="Personal Settings">


 <ListPreference
 android:title="Gender"
 android:summary="Verify or deny the presence of a Y chromosome."
 android:key="genderPref"
 android:defaultValue="male"
 android:entries="@array/genderArray"
 android:entryValues="@array/genderValues" />

 <ListPreference
 android:title="Weight"
 android:summary="How much the planet pulls on you, in pounds."
 android:key="weightPref"
 android:defaultValue="180"
 android:entries="@array/weightArray"
 android:entryValues="@array/weightValues" />

 </PreferenceCategory>

<PreferenceCategory android:title="Drink Settings">

 <ListPreference
 android:title="Beer Size"
 android:summary="The volume of your beer, in ounces."
 android:key="beerPref"
 android:defaultValue="12"
 android:entries="@array/beerArray"
 android:entryValues="@array/beerValues" />

 <ListPreference
 android:title="Shot Size"
 android:summary="The volume of your shot, in ounces."
 android:key="shotPref"
 android:defaultValue="1.5"
 android:entries="@array/shotArray"
 android:entryValues="@array/shotValues" />

 <ListPreference
 android:title="Wine Size"
 android:summary="The volume of your wine, in ounces."
 android:key="winePref"
 android:defaultValue="5"
 android:entries="@array/wineArray"
 android:entryValues="@array/wineValues" />


 </PreferenceCategory>
 </PreferenceScreen>

转到权重ListPreference:

alt text

然后就显示出来了。这些值作为字符串数组存储在 res/values/arrays.xml 中。这是一个示例,仅包含重量:

<string-array name="weightArray">
<item>120 lbs</item>
<item>150 lbs</item>
<item>180 lbs</item>
<item>210 lbs</item>
<item>240 lbs</item>
<item>270 lbs</item>
 </string-array>
 <string-array name="weightValues">
<item>120</item>
<item>150</item>
<item>180</item>
<item>210</item>
<item>240</item>
<item>270</item>
 </string-array>

这基本上是我所得到的。当然,我可以单击一个值,但它不会更改公式,因为它没有与我在 DrinkingBuddy.java 中创建的双精度数链接。设置中显示的所有内容目前都只是空壳,包括主布局上的微调器(默认时间仅设置为 1 小时)

我确实创建了一个 Preferences.java 并尝试实现在中找到的各种代码组合网络上的教程和资源,但无济于事。无论如何,这里充满了使 beerPref (更改啤酒数量的设置选项)与我的主类中的变量相关联的失败尝试:

package com.dantoth.drinkingbuddy;


 import android.app.Activity;
 import android.content.SharedPreferences;
 import android.os.Bundle;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
 import android.preference.Preference.OnPreferenceClickListener;


 public class Preferences extends PreferenceActivity {

public static final String PREF_BEER_SIZE = "PREF_BEER_SIZE";

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

 //Get the custom preference



 Preference beerPref = (Preference) findPreference("beerPref");
 beerPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

 public boolean onPreferenceClick(Preference preference) {

 SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
 SharedPreferences.Editor editor = customSharedPreference.edit();

 editor.commit();
 return true;
 }}

 );}
 }

完整的教程和示例代码将非常棒,因为我还没有在那里找到任何可靠的指南。

I've really been struggling through this. New to Java/Android. I'm writing my first app and this is the first thing that has taken me longer than a couple days of searching to figure out. Here's the setup: It's a BAC calculator / drink counter:

alt text

A formula is used to calculate the BAC. Here's the forumla:

Bac = ((StandardDrinks / 2) * (GenderConstant / Weight)) - (0.017 * Hours);

So as you can see, being able to modify the gender and weight will produce more accurate and personalized results. So I have them as doubles:

double GenderConstant = 7.5; //9 for female
double Weight = 180;

To change these variables I would like the person to be able to go into the settings and choose different values. I have these things set up, but not linked to the variables shown above because I cannot for the life of me figure out how. Here they are:

alt text

I press the menu button and this pops up. Great. I'll click Settings.

alt text

Now the preferences pops up. Here is my preferences.xml:

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

 <PreferenceCategory android:title="Personal Settings">


 <ListPreference
 android:title="Gender"
 android:summary="Verify or deny the presence of a Y chromosome."
 android:key="genderPref"
 android:defaultValue="male"
 android:entries="@array/genderArray"
 android:entryValues="@array/genderValues" />

 <ListPreference
 android:title="Weight"
 android:summary="How much the planet pulls on you, in pounds."
 android:key="weightPref"
 android:defaultValue="180"
 android:entries="@array/weightArray"
 android:entryValues="@array/weightValues" />

 </PreferenceCategory>

<PreferenceCategory android:title="Drink Settings">

 <ListPreference
 android:title="Beer Size"
 android:summary="The volume of your beer, in ounces."
 android:key="beerPref"
 android:defaultValue="12"
 android:entries="@array/beerArray"
 android:entryValues="@array/beerValues" />

 <ListPreference
 android:title="Shot Size"
 android:summary="The volume of your shot, in ounces."
 android:key="shotPref"
 android:defaultValue="1.5"
 android:entries="@array/shotArray"
 android:entryValues="@array/shotValues" />

 <ListPreference
 android:title="Wine Size"
 android:summary="The volume of your wine, in ounces."
 android:key="winePref"
 android:defaultValue="5"
 android:entries="@array/wineArray"
 android:entryValues="@array/wineValues" />


 </PreferenceCategory>
 </PreferenceScreen>

Onward to the weight ListPreference:

alt text

And that shows up. The values are stored as string-arrays in res/values/arrays.xml. Here's a sample, of just the weight ones:

<string-array name="weightArray">
<item>120 lbs</item>
<item>150 lbs</item>
<item>180 lbs</item>
<item>210 lbs</item>
<item>240 lbs</item>
<item>270 lbs</item>
 </string-array>
 <string-array name="weightValues">
<item>120</item>
<item>150</item>
<item>180</item>
<item>210</item>
<item>240</item>
<item>270</item>
 </string-array>

This is basically as far as I've gotten. I can click a value, sure, but it doesn't change the formula because it's not linked with the doubles I created in DrinkingBuddy.java. All of the stuff displayed in the settings are just empty shells for now, including the spinner on the main layout (the default time is just set to 1 hour)

I did create a Preferences.java and have tried implementing various combinations of code found in tutorials and resources around the web, but to no avail. Here it is anyway, filled with failed attempts to make beerPref (the settings option to change how many ounces in the beer) correlate with a variable in my main class:

package com.dantoth.drinkingbuddy;


 import android.app.Activity;
 import android.content.SharedPreferences;
 import android.os.Bundle;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
 import android.preference.Preference.OnPreferenceClickListener;


 public class Preferences extends PreferenceActivity {

public static final String PREF_BEER_SIZE = "PREF_BEER_SIZE";

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

 //Get the custom preference



 Preference beerPref = (Preference) findPreference("beerPref");
 beerPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

 public boolean onPreferenceClick(Preference preference) {

 SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
 SharedPreferences.Editor editor = customSharedPreference.edit();

 editor.commit();
 return true;
 }}

 );}
 }

A full on tutorial and sample code would be AWESOME as I've yet to find any reliable guides out there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

汹涌人海 2024-09-12 00:45:48

我仍在自己解决所有这些问题,但是(在某种程度上改编自我的版本)我认为您的 Preferences 类只需要执行以下操作:

public class Preferences extends PreferenceActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // load the XML preferences file
        addPreferencesFromResource(R.xml.preferences);
    }
}

然后在您的主类中,您可以参考首选项:

public class DrinkingBuddy extends Activity 
                           implements OnSharedPreferenceChangeListener {

    private int weight;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        // register preference change listener
        prefs.registerOnSharedPreferenceChangeListener(this);

        // and set remembered preferences
        weight = Integer.parseInt((prefs.getString("weightPref", "120")));
        // etc
    }

    // handle updates to preferences
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        if (key.equals("weightValues")) {
            weight = Integer.parseInt((prefs.getString("weightPref", "120")));
        }
        // etc
    }
}

处理首选项更新的保存为你。

(不太确定公共/私人声明!)

I'm still working all this out myself, but (somewhat adapted from my version) I think your Preferences class only needs to do the following:

public class Preferences extends PreferenceActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // load the XML preferences file
        addPreferencesFromResource(R.xml.preferences);
    }
}

Then in your main class, you can refer to the preferences:

public class DrinkingBuddy extends Activity 
                           implements OnSharedPreferenceChangeListener {

    private int weight;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        // register preference change listener
        prefs.registerOnSharedPreferenceChangeListener(this);

        // and set remembered preferences
        weight = Integer.parseInt((prefs.getString("weightPref", "120")));
        // etc
    }

    // handle updates to preferences
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        if (key.equals("weightValues")) {
            weight = Integer.parseInt((prefs.getString("weightPref", "120")));
        }
        // etc
    }
}

The saving of preference updates is handled for you.

(Not too sure about public/private declarations!)

宛菡 2024-09-12 00:45:48

您可能正在请求两组不同的首选项文件。

确保将 ListPreference 值存储在同一文件中。
启动 adb 滚动到 cd /data/data/com.your.package 并查找类型首选项的文件夹和文件。

我认为错误在于您指定的文件与保存设置的文件不同:

尝试将其更改为:

SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

然后

SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(context);

您可能只需要查询

preferences.getString('weightPref', null);

此外您不需要编辑器。首选项会自动保存。

You are requesting probably two different set of preference files.

Make sure you store the ListPreference values in the same files.
Start up adb roll to the cd /data/data/com.your.package and look for folders and files of type preferences.

I think the bug is that you specify a different file than the one the setting has been saved too:

Try changing this:

SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

to

SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(context);

Then you will probably have to query only

preferences.getString('weightPref', null);

Also you do not need the Editor. The preferences are saved automatically.

情痴 2024-09-12 00:45:48

对于大多数应用程序来说,使用默认共享首选项是最方便的。您可以通过以下方式从应用程序中的任何位置获取它们:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

您可以使用以下方式将新变量保存到其中:

sp.edit().putString("var_name", "var value".apply();

For most apps, it is most convinient to use the default shared preferences. You can get from anywhere in you app them with:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

You can save new variables into it with:

sp.edit().putString("var_name", "var value".apply();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文