Android中,View在layout文件的onClick属性值,是如何找到对应的onClick方法过程(个人理解)

Activity类通过布局id找到布局文件后,对各个组件进行布局,其中就包括View的创建。
View的创建会通过方法 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes)
传递的参数:
1. 其中后面两个参数,在View类的内部都是传了02. attrs则是View的属性集;
3. context是调用这个View的上下文,这里就理解为创建布局文件的Activity类吧。

View类中,通过 mSourceLayoutId = Resources.getAttributeSetSourceResId(attrs);
获取到View所属布局的id;
再通过
	final TypedArray a = context.obtainStyledAttributes(
		attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
将attrs中的属性值存进数组a中。这为后面轮询属性值做准备

接下来会通过轮询的方式查看a中有哪些属性,格局对应的属性来进行相对应的方法,如下的是onClick,如果在布局文件中设计了onCLick属性,这会走到下面这个位置,通过attr属性找到对应的属性值,然后利用这个属性值(方法名)去寻找方法
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
	int attr = a.getIndex(i);
	switch (attr) {
     ...
		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 DeclaredOnClickListener(this, handlerName));
   		}
   		break;
	...
	}
}
a中的index跟View的属性值是一一对应的,但轮询到onClick属性值后,会通过方法
setOnClickListener(new DeclaredOnClickListener(this, handlerName))
来设置监听点击的方法名。

下面的hostView其实就是View本身
public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
  	mHostView = hostView;
    mMethodName = methodName;
}


@Override
public void onClick(@NonNull View v) {
   if (mResolvedMethod == null) {
       resolveMethod(mHostView.getContext(), mMethodName);
   }
   ...
}
然后通过方法名去查找对应的方法,下面就是查找的具体实现
private void resolveMethod(@Nullable Context context, @NonNull String name) {
	...
	            final Method method = context.getClass().getMethod(mMethodName, View.class);
	            if (method != null) {
	                mResolvedMethod = method;
	                mResolvedContext = context;
	                return;
	            }

	 ...
}

final Method method = context.getClass().getMethod(mMethodName, View.class);
这里的通过利用上下文,也就是设置布局的类,去获取到该类中对应方法名mMethodName及参数为View的方法。
这样就完成了onClick的属性值布置了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值