سؤال

The android resource ID is often used as a way to get/modify an XML-defined layout component. Is it acceptable to use them purely as unique identifiers for any Java code in your Android application? For example:

Using Android Resource IDs

ids.xml

<item name="sensor_pressure" type="id"/>
<item name="sensor_humidity" type="id"/>
<item name="sensor_precision_gas" type="id"/>

Sensor.java

public Sensor(int sensorId) {
    initializeSensor(sensorId);
}

private void determineSensorType(int sensorId) {
    switch(sensorId) {
    case R.id.sensor_pressure:
        intializePressureSensor();
        break;
    case R.id.sensor_humidity:
        initializeHumiditySensor();
        break;
    // etc...
    }
}

Or would it be preferable to do things in pure Java? For example:

Using Only Java

Sensor.java

public Sensor(int sensorId) {
    initializeSensor(sensorId);
}

enum SensorType {
    PRESSURE, HUMIDITY, PRECISION_GAS
}

private void determineSensorType(SensorType sensorType) {
    switch(sensorType) {
    case SensorType.PRESSURE:
        intializePressureSensor();
        break;
    // etc...
    }
}

Best Solution For My Example:

From MaciejGórski below. Using an interface, one can solve the problem posed by ridding of the need of unique IDs completely.

public interface Sensor {

}

public class HumiditySensor implements Sensor {

    public HumiditySensor() {
        init();
    }
}
هل كانت مفيدة؟

المحلول

How about an object oriented way?

public interface Sensor {

}

public class HumiditySensor implements Sensor {

    public HumiditySensor() {
        init();
    }
}

You can avoid having ugly switch statements in many places in your code.

نصائح أخرى

Is it acceptable to use them purely as unique identifiers for any Java code in your Android application?

It certainly works, but...

Or would it be preferable to do things in pure Java?

I'd go with this approach. If nothing else, the enum prevents you from getting your identifiers mixed up with other integers.

It's certainly doable, but I can't think of a single benefit of putting some kind of contants/ids in a resource file. Using enums allow you to group related constants and it helps you avoid accidentally mixing unrelated constants.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top