在一个Activity 里面,如果调用下面的代码:
View view = LayoutInflater.from(this).inflate(R.layout.activity_xxxx, null);
View view = view.findViewById(R.id.xxxxxx);
Activity activity = (Activity)view.getContext();
这样写是没有问题的;this 就是当前的Activity,所以不会出错;
当时如果代码改一下,问题就来了:
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_xxxx, null);
View view = view.findViewById(R.id.xxxxxx);
Activity activity = (Activity)view.getContext();
如果这样写,哪问题就来了,XXXApplication not cast to Activity ;(转换异常)
所有的控件都有都会记录自己是来自哪里的(getContext()),所以强转换的注意点;