从Android的微调选择的项目,使用它 [英] Selecting Item from Android Spinner and Using It

查看:258
本文介绍了从Android的微调选择的项目,使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从枚举填充一个微调:

I have a spinner which is populated from an Enum:

public enum Frequencies
    {
    EVERYDAY("Every day"), EVERYOTHERDAY("Every second day");

    private String friendlyName;

    private Frequencies(String friendlyName)
    {
        this.friendlyName = friendlyName;
    }

    @Override public String toString()
    {
        return friendlyName;
    }
    };

的toString()覆盖意味着微调显示用户友好的名称。

The toString() overrides means the spinner displays user friendly names.

微调器填充像这样:

        ArrayAdapter<Frequencies> adapter = new ArrayAdapter<Frequencies>(this, android.R.layout.simple_spinner_item, 
            Frequencies.values());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    newAlarmFreqSpinner.setAdapter(adapter);

这一切运作良好。当用户从选择微调的频率,我想使用的值设置价值重新present报警之间的间隔在一个简单的报警对象。因此,对于每一天的价值会在一天的秒数。

All of this is working well. When the user chooses a frequency from the spinner, I'd like to use the value to set a long value to represent the interval between alarms in a simple Alarm object. So the value for "Every day" would be the number of seconds in one day.

不过,我不能完全得到我围绕着如何很好地处理频率对象我从微调检索头。我最初的想法是使用开关语句上显示的字符串开关,确定long值我需要的,但你当然不能够开关的字符串。

However, I can't quite get my head around how to elegantly handle the Frequency object I retrieve from the spinner. My initial thought was to use a switch statement to switch on the displayed string to determine the long value I require, but of course you can't switch on a string.

然后我试图修改频率枚举所以每个条目存储在其自己的long值:

I then tried modifying the Frequencies enum so each entry stored its own long value:

    EVERYDAY("Every day", 86400), EVERYOTHERDAY("Every second day", 86400 * 2);

private String friendlyName;
public final int intervalInSecs;

private Frequencies(String friendlyName, int intervalInSecs)
{
    this.friendlyName = friendlyName;
    this.intervalInSecs = intervalInSecs;
}...

但随后的开关抱怨说,案件前pressions必须恒定前pressions(尽管我做了 intervalInSecs最后

    Object obj = newAlarmFreqSpinner.getSelectedItem();
    switch(((Frequencies)obj).getIntervalInSecs())
{
    case Frequencies.EVERYDAY.intervalInSecs: //Java doesn't like this
    {

        break;
    }...

我敢肯定,我在做这个难度比它确实是!我倒是AP preciate任何想法。

I'm sure I'm making this more difficult than it really is! I'd appreciate any ideas.

推荐答案

嗯,基本上枚举类型都有它的关联间隔。所以,你不需要在区间切换,只是在枚举类型切换:

Well basically the enum type has it's associated interval. So you don't need to switch on the interval, just switch on the enum type:

Object obj = newAlarmFreqSpinner.getSelectedItem();
switch((Frequencies)obj) {
case Frequencies.EVERYDAY {
    alarm.setInterval(EVERYDAY.getIntervalInSecs());
    break;
}...

这篇关于从Android的微调选择的项目,使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆