Lint错误:将findViewById作为参数传递的WrongViewCast

Dal*_*kar 6 java android lint android-studio

自从我更新到Android Studio 3.0后,拒绝构建发布APK并抛出lint WrongViewCast错误.在2.x和以前的版本中没有.

问题是在违规代码中将结果findViewById作为参数传递给构造函数期望View实例.由于所有视图都来自View类并且findViewById本身返回,View因此这是相当意外的情况.

产生lint WrongViewCast错误的代码是相当基本的:

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

ViewWrapper.java

import android.view.View;

public class ViewWrapper
{
    private View contentView;

    public ViewWrapper(View content)
    {
        contentView = content;
    }
}
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // this line shows WrongViewCast error
        ViewWrapper v = new ViewWrapper(findViewById(R.id.text)); 
    }    
}
Run Code Online (Sandbox Code Playgroud)

用以下代码替换上面有问题的代码行不会引发错误

    View tv = findViewById(R.id.text);
    ViewWrapper v = new ViewWrapper(tv);
Run Code Online (Sandbox Code Playgroud)

当然,使用@SuppressLint("WrongViewCast")注释或使用gradle来抑制lint错误

lintOptions {
    disable 'WrongViewCast'
}
Run Code Online (Sandbox Code Playgroud)

也行得很好.

问题是为什么ViewWrapper v = new ViewWrapper(findViewById(R.id.text));显示错误?是lint中的那个bug还是我遗漏了一些明显的东西?