【发布时间】:2013-12-09 11:33:44
【问题描述】:
我有自定义组件扩展了 LinearLayout。我需要创建属性来为这个组件放置自定义方法。我需要在组件内部调用它。
像按钮一样。
<Button android:onClick="customMethod"/>
如何解决?
【问题讨论】:
我有自定义组件扩展了 LinearLayout。我需要创建属性来为这个组件放置自定义方法。我需要在组件内部调用它。
像按钮一样。
<Button android:onClick="customMethod"/>
如何解决?
【问题讨论】:
【讨论】:
查看Android java文件中View类的源码可以发现如下
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 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);
}
}
});
}
break;
getMethod 方法应该是您正在寻找的。p>
【讨论】: