Is there a way to show some warning/error when Android resource id does not belong to layout inflated in Activity?
Following is simple example, but in more complex layouts it is much harder to track down such issues as they can only be found during run-time. I would like to be able to catch them at compile-time.
MainActivity initialization
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// how to prevent erroneous usage of R.id.text2 at compile time
TextView t = (TextView) findViewById(R.id.text2);
}
activity_main.xml
<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/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
activity_second.xml
<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=".SecondActivity">
<TextView android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .
onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.
You can declare a layout in two ways: Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. You can also use Android Studio's Layout Editor to build your XML layout using a drag-and-drop interface.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
I don't know about any Lint checks or similar which can do what you require. I'd make a feature request because it looks like a useful feature.
For the time being I'd use prefixes in identifiers. E.g.:
findViewById(act_main_text1);
findViewById(act_main_text2);
root.findViewById(fragment_preferences_username);
And so on. It won't raise the error/warning during the build stage, but it'll make your life easier as you'll always know which activity/fragment/view this particular id belongs to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With