Android switch报错:Resource IDs cannot be used in a switch statement in Android library modules

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wengwuhua/article/details/84673316

报错情况

在开发过程中使用实现多个按钮监听的时候,重写onClick方法,在其中需要根据按钮ID判断按下的是哪个按钮,一般我们用switch来代替if else来判断,如下:

 @Override
        public void onClick(View v) {
            int position = (Integer) ((Button) v).getTag();
            int id = v.getId();
            switch (id){
                case R.id.btn1:
                Log.i(TAG, "按下btn1");
                    break;
                case R.id.btn2:
                Log.i(TAG, "按下btn2");
                    break;
            }
        }

但有一次在工程中这样用的时候却发现报错了,提示Resource IDs cannot be used in a switch statement in Android library modules。看了详细的报错提示:Validates using resource IDs in a switch statement in Android library module. Resource IDs are non final in the library projects since SDK tools r14, means that the library code cannot treat these IDs as constants.

报错原因

原来是因为我们是在library模块中使用的switch case,而case中的条件又是R.id.xxx,从提示可以知道冲SDK14后开始,library中的资源ID即R.id.xxx就不是final类型,也就是说在library中,它不能被当作一个常量。而我们知道在switch case语句中,case后必须是常量,所以才会报错。
这里注意一下,R.id.xxx这些资源ID只有在主模块中才是final类型的,而在引入的module(library)中不是final。

解决方法

既然不能在library中使用switch case来判断资源ID,那就改成if else就好了

猜你喜欢

转载自blog.csdn.net/Wengwuhua/article/details/84673316