我希望我的自定义视图具有可以通过XML设置的属性,该属性定义了此视图支持的某些自定义行为的回调。
我知道我可以使用反射调整一个简单的字符串,但它存在于android API中,因为Button有android:onClick所以我想知道这是否是我可以开箱即用而不是重新发明轮子
任何熟悉它是如何完成的人或者我必须继续使用refelections自行实现它吗?
答案 0 :(得分:0)
看到android source code,看起来就像我要做的那样:
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void More ...onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
所以我猜这是唯一的方法......