Alternate and fast replacement of findViewById in android

Viewed 11647

How I can avoid using findViewById in my app. Layout is very complicated and findViewById traverses its tree to find view which takes time and it is used several times.

6 Answers

you can directly import views from xml:-

add kotlin extentions in app.gradle

apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

see the below eg.

enter image description here

enter image description here

You can use viewbinding to replace findviewbyid. It will help you to avoid null pointer exception and type cast exception. You just need to enable view binding in modules gradle file. Then create instance for binding class. then use that instance to reference views in your code. You will get much clear information from these links.

View binding video tutorial : https://youtu.be/ILUf3Zf0ocI

View binding documentation : https://developer.android.com/topic/libraries/view-binding

How I can avoid using findViewById in my app

You can use getChildAt as alternative for findViewById for founding a view inside a ViewGroup and its derivative (like RelativeLayout, LinearLayout, etc). It is super fast because it's only try to find the view from the views array by its index (link to the source code):

// Child views of this ViewGroup
private View[] mChildren;

// Number of valid children in the mChildren array, the rest should be null or not
// considered as children
private int mChildrenCount;

...

public View getChildAt(int index) {
    if (index < 0 || index >= mChildrenCount) {
        return null;
    }
    return mChildren[index];
}

The following is the sample how using getChildAt. Assume you have the following Layout:

<RelativeLayout>
   <TextView/>
   <Button/>
   <EditText/>
</RelativeLayout>

you can get all the views with the following:

// assume we have inflate the layout
TextView textView = (TextView) getChildAt(0);
Button button = (Button) getChildAt(1);
EditText editText = (EditText) getChildAt(2);

But then it is started to become tedious if you have complex layout like the following:

<RelativeLayout>
   <TextView/>
   <Button/>

   <LinearLayout>
       <TextView/>
       <Button/>
       <EditText/>
   </LinearLayout>

   <LinearLayout>
       <TextView/>
       <Button/>
       <EditText/>
   </LinearLayout>

</RelativeLayout>

The major problem of using getChildAt is you can't easily change your layout position without adapting your code for the change.

Related