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)
4

3 に答える 3

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

String "R.layout.yourLayoutId" は数値ではなく、その文字列であるため、NumberFormatException が返されます。layoutName の id を見つけるには、次を使用します。

getResources().getIdentifier("YOUR_LAYOUT_NAME",
                "layout", context.getPackageName());
于 2012-07-23T11:49:43.273 に答える
1

setTabBarに渡された文字列から整数を解析しようとしています。変数名を実際の値に変換するにはリフレクションが必要であり、私は個人的にそのウサギの穴を踏みにじりたくありません。

渡されるパラメーターが整数であることを指定しないのはなぜですか?

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

そして、呼び出し側のクラスでは:

activity.setTabBar(R.layout.nifty_layout);
于 2012-07-23T11:53:38.930 に答える
0

このようなものが機能するはずです:

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;
    }
}

これがあなたが望んでいたものかどうかはわかりません。これがお役に立てば幸いです。

于 2012-07-23T11:54:39.320 に答える