Question

We started an informal Android development group at work. We'll each be adding semi-independent Activities to a single app. Goofing around yesterday, the best I could come up with to make this 'easy' was to have our main activity be a GridView and allow developers to 'register' their Activities in the main Activity via an element in a hard-coded array of 'ActionItems':

    private final ActionItem[] actionItems = {
        new ActionItem(R.drawable.dms_to_dd, "DMS to/from DD", DegreeConverter.class)
    };

where an ActionItem is just this:

public class ActionItem {

    private int drawingID;
    private String label;
    private java.lang.Class<?> activity;

    public ActionItem(int drawingID, String label, Class<?> activity) {
        this.drawingID = drawingID;
        this.label     = label;
        this.activity  = activity;
    }

    public int getDrawingID() {
        return drawingID;
    }
    public String getLabel() {
        return label;
    }
    public Class<?> getActivity() {
        return activity;
    }   
}

To get people started I created the first simple Activity/ActionItem and it is registered as shown above.

We want the drawable to be there for the image in the GridView and the String for labeling and, most importantly, the class that will be launched through an Intent when the corresponding GridView item is selected.

All of this works. However, it would be nice if folks didn't have to edit the main Activity to make this work. I was hoping we could read this same information (for the ActionItem) from a text file before populating the GridView. The drawable id and the String are no problem. So the main question: How might we specify that class in a text file?

Is there someway to create a java.lang.Class instance from a name (String/char[])? Is there some better way to do what I've described above?

Happy to provide further details if helpful.

Was it helpful?

Solution

Have you tried with:

  Class.forName("com.something.MyClass")

http://developer.android.com/reference/java/lang/Class.html#forName(java.lang.String)

You can read the name from a file, and set the string in the forName method.

So, you can do something like this:

  public ActionItem(int drawingID, String label, String activityClassName) {
    this.drawingID = drawingID;
    this.label     = label;
    this.activity  = Class.forName(activityClassName);
}

OTHER TIPS

Using reflection, an example below:

Class theClass  = Class.forName("YourClass");
YourClass instancevariable = (YourClass)theClass.newInstance();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top