我在 Ubuntu 上使用 eclipse + Android SDK。
我想打印传感器类型设备的名称,有 很多他们,我想自动完成。
如果我使用 a,
Log.d("SENSORTYPE","Type: " + tempSensor.getType())
我会打印 (int) 类型,但我想要枚举的名称。
我怎么能这么做呢?
I'm using eclipse + Android SDK on Ubuntu.
I would like to print the name of a sensor type device, there a a lot of them and I want to do it automatically.
If I use a
Log.d("SENSORTYPE","Type: " + tempSensor.getType())
I print the (int) type, but I would like the name of the enum.
How could I do that?
发布评论
评论(3)
您可以引入一个
abstract
方法并在每个枚举
中实现它。这种方式为您提供了更大的灵活性,例如,如果您不想显示其编程名称
you can introduce an
abstract
method and implement it in everyenumeration
This way gives you more flexibility, for example, if you don't want to display its programmatic name
对于枚举,您可以获取所有常量的数组,并使用如下代码轻松循环它们:
但是,Sensor 类不是枚举,而是包含常量列表。如果不指定所有常量名称,则无法像枚举一样以编程方式循环该列表。
但是,您可以创建一个静态查找,将整数映射到要使用的字符串值,例如
您可以这样使用:
这种方法确实意味着您仍然需要写出每个常量,并在常量发生变化时更新列表,但您只需要做一次。将查找包装在某种辅助方法或类中是一个好主意,具体取决于您想要重用它的范围。
For enumerations, you can obtain an array of all the constants and loop over them very easily using code such as this:
However, the Sensor class you link to isn't an enumeration, but contains a list of constants. There's no way to programatically loop over that list like an enumeration without specifying all the constants names.
However, you can create a static lookup that maps the ints to the String value you want to use, for example
You can use this like this:
This approach does mean you still have to write out each constant and update the list if the constants change, but you only have to do it once. It'd be a good idea to wrap the lookup in some kind of helper method or class depending on how widely you want to reuse it.