2 u012131702 u012131702 于 2015.06.26 08:41 提问

android中的xml里实现onClick=“clickButton” 在java中……

1.对Android中的xml实现onClick有点疑问,实现的原理是怎样的?
2.java中实现是这样的:
view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

3.xml结合java的实现样式比较好看,可是他没有实现OnClickListener的接口呢
setOnClick="function"
public void function(View view){

}

1个回答

u012131702
u012131702   2015.06.26 08:55
已采纳
           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;
Csdn user default icon
上传中...
上传图片
插入图片