Since I upgraded to Android Studio 3.0, it refuses to build an APK release and throws lint WrongViewCasterrors. In versions 2.x and previous versions they were not.
The problem is that when code is violated, the result findViewByIdis passed as a parameter to the constructor that is waiting for the instance View. Since all views descend from the class Viewand findViewByIdreturn itself View, this is a rather unexpected scenario.
The code that creates the lint error WrongViewCastis pretty simple:
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>
ViewWrapper.java
import android.view.View;
public class ViewWrapper
{
private View contentView;
public ViewWrapper(View content)
{
contentView = content;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewWrapper v = new ViewWrapper(findViewById(R.id.text));
}
}
Replacing the above line of code with the following does not cause an error
View tv = findViewById(R.id.text);
ViewWrapper v = new ViewWrapper(tv);
, lint @SuppressLint("WrongViewCast") gradle
lintOptions {
disable 'WrongViewCast'
}
.
: ViewWrapper v = new ViewWrapper(findViewById(R.id.text)); ? lint - ?