0

I got a superclass like this:

public class SuperClass extends Activity

and a child class

 public class ChildClass extends SuperClass

The SuperClass contains a function to set a layout

public void setTabBar(String layout){
    inflater.inflate(...., ...); 
}

The only thing that different in my child class and superclass is the layout. So over to my question:

Is there anyway I can send a String to the superclass method setTabBar("name of the layout"); and then spesify the layout. I'v tried this:

public void setTabBar(String layout) {

        int layoutFromString = Integer.parseInt("R.layout."+layout);
        inflater.inflate(layoutFromString, null);
}

But this doesnt seems to work. Any ideas?

EDIT

As mentioned I tried this:

  public void setTabBar(int id) {
     inflater.inflate(id, null);
  }

This will work for the SuperClass, but when I call the function from the child class like this:

public class TestClass extends SuperClass{

  @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setTabBar(R.layout.test); 

  }
}

LogCat only outputs this:

07-23 13:57:15.775: E/AndroidRuntime(7329):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143

3 Answers3

4
int layoutFromString = Integer.parseInt("R.layout."+layout);

gives you a NumberFormatException, because String "R.layout.yourLayoutId" not a number, its String. To find id for layoutName use:

getResources().getIdentifier("YOUR_LAYOUT_NAME",
                "layout", context.getPackageName());
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34
1

You're trying to parse an integer from the string passed in to setTabBar. Reflection would be required to convert the variable name to the actual value, and I personally wouldn't want to tread down that rabbit hole.

Why not just specify that the parameter passed in is an integer?

public void setTabBar(int layoutId) {
    inflater.inflate(....,....);
}

And, in the calling class:

activity.setTabBar(R.layout.nifty_layout);
0

Something like this should work:

public abstract class SuperClass extends Activity{
    public void setTabBar(String layout){
        inflater.inflate(getResId(), null); 
    }

    protected abstract int getResId();
}

public class ChildClass extends SuperClass{
    @Override
    protected abstract int getResId(){
        return R.layout.child;
    }
}

I'm not sure this is what you wanted. I hope this will help you.

AMerle
  • 4,354
  • 1
  • 28
  • 43