Dynamically Add Fields to Java Class in Android

Viewed 49

Android Java;

I would like to be able to add fields to a class based on condition. Such fields is TextView, it can be one or more. I don't want to declare redundant ones.

class VieHolder{
TextView textView1;
// textView2, textView3, ... textViewN based on condition

...
}

Solution should not include additional dependency!

1 Answers

Java doesn't support such a thing as the dynamic property instead, you could use an internal Map to store properties, like this:

public class ViewHolder {
    private HashMap<String, Object> properties;

    //Create object with properties
    public ViewHolder(HashMap<String, Object> properties) {
        this.properties = properties;
    }

    //Set properties
    public Object setProperty(String key, Object value) {
        return this.properties.put(key, value); //Returns old value if existing
    }

    //Get properties
    public Object getProperty(String key) {
        return this.properties.getOrDefault(key, null);
    }
}

but this way doesn't look suit. if you wanna build a recyclerView of textFields you'd better put each textField as an item

Related