我正在开发一个用作其他应用程序模板的应用程序,我需要创建一个带有类别的菜单(类别因应用程序而异)。我想要的是动态创建菜单。在一个JSON
文件中,我定义了必要的类别并在屏幕上动态创建项目。我打算做的是设置每个类别(Button
)a Listener
,以便当您单击每个类别时执行不同的操作。为此,我正在使用Reflection
. 这是我打算做的代码示例。
package com.example;
public class MainActivity extends Activity {
Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(CustomListener.create("MakeCallListener"));
}
static class CustomListener {
public static OnClickListener create(String listenerName) {
OnClickListener actionListener = null;
try {
Class<?> classListener = Class
.forName("com.example.MainActivity$" + listenerName);
actionListener = (OnClickListener) classListener.newInstance();
} catch (ClassNotFoundException e) {
Log.i("debug", e.getMessage());
} catch (IllegalAccessException e) {
Log.i("debug", e.getMessage());
} catch (InstantiationException e) {
Log.i("debug", e.getMessage());
} catch (IllegalArgumentException e) {
Log.i("debug", e.getMessage());
}
return actionListener;
}
}
class MakeCallListener implements OnClickListener {
public MakeCallListener() {}
@Override
public void onClick(View v) {
/*
* TODO: write the procedure to dial a phone number
*/
}
};
}
问题是我得到一个InstatiationException
. 错误信息是:
01-01 03:00:25.683: I/Bluumi(14206): 无法实例化类 com.example.MainActivity$MakeCallListener; 没有空的构造函数
我几乎没有使用反射的经验,我尝试过的解决方案不起作用。
这是堆栈跟踪
java.lang.InstantiationException: can't instantiate class com.example.MainActivity$MakeCallListener; no empty constructor
java.lang.Class.newInstanceImpl(Native Method)
java.lang.Class.newInstance(Class.java:1319)
com.example.MainActivity$CustomListener.create(MainActivity.java:36)
com.example.MainActivity.onCreate(MainActivity.java:21)
android.app.Activity.performCreate(Activity.java:4465)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
android.app.ActivityThread.access$600(ActivityThread.java:127)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4507)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
dalvik.system.NativeStart.main(Native Method)