秒懂Android開發之ViewBinding,一代神器ButterKnife的終結者

【版權申明】非商業目的可自由轉載
博文地址:https://blog.csdn.net/ShuSheng0007/article/details/103246642
出自:shusheng007

本文於2020/04/28更新

概述

Android大神 JakeWharton 開發的一代神器 ButterKnife 即將落幕了。怎麼回事呢?就是因爲View Binding 的橫空出世。在那個滿屏都是findViewById的蠻荒年代,JakeWharton 大神給我們送來了神器ButterKnife,使我們從石器時代進化到了青銅時代,這次ViewBinding是不是又將使我們跨越到一個全新的時代呢,讓我們拭目以待。話說編程正在變的越來越簡單,估計再過10年,軟件開發將是是小學生的必備技能了。

對了,ButterKnife 即將落幕可不是我說的,大家不要噴我,是大神自己在此項目的ReadMe上說的:

Attention: Development on this tool is winding down. Please consider switching to view binding in the coming months.

那讓我們一起看看這個牛逼乎乎的東東吧。

ViewBinding

本文力求說明如下幾個問題:

  1. ViewBinding 解決什麼問題?
  2. 如何使用?
  3. 與現有方法相比較的優勢?
  4. 什麼原理?

相信弄懂了上面幾個問題,基本上也就抓住了ViewBinding的精髓了,希望你可以在此基礎上更近一步:給Google提出一些改進方案,這一步貌似有點難…

注意:要使用ViewBinding功能,AndroidStudio至少要升級到3.6,建議直接使用 AS4.0 現在已經到BATA5了,穩定版即將發佈

解決什麼問題

顧名思義ViewBinding的意思就是如何將view代碼綁定在一起。所以其主要解決如何安全優雅地從代碼中引用到XML layout文件中的view控件的問題。直到目前爲止,Android構建用戶界面的主流方式仍然是使用XML格式的layout文件。

如何使用

ViewBinding實在是太容易上手了,幾乎沒有使用成本。

  • 在要使用ViewBinding的 module 的gradle文件中開啓ViewBinding
    使用AS 3.6.x 的使用如下方法開啓

    	android {
    		...
    	     viewBinding{
    	        enabled = true
    	  	}
    	}
    

    使用AS 4.0.x 的使用如下方法開啓

    	android {
    		...
    	    buildFeatures{
    	        viewBinding= true
    	    }
    	}
    
  • 編譯此module獲得XMLlayout文件對應的綁定類

    在gradle文件中開啓ViewBinding功能後,編譯此module。編譯器就會爲此模塊下的每個layout文件都產生一個對應的綁定類。

    假設我們有如下XMLlayout 文件

    	<?xml version="1.0" encoding="utf-8"?>
    	<androidx.constraintlayout.widget.ConstraintLayout
    	    xmlns:android="http://schemas.android.com/apk/res/android"
    	    xmlns:app="http://schemas.android.com/apk/res-auto"
    	    xmlns:tools="http://schemas.android.com/tools"
    	    android:layout_width="match_parent"
    	    android:layout_height="match_parent"
    	    tools:context=".DescriptionActivity">
    	
    	    <ImageView
    	        android:id="@+id/img_backgroud"
    	        android:layout_width="0dp"
    	        android:layout_height="250dp"
    	        android:scaleType="centerCrop"
    	        app:layout_constraintEnd_toEndOf="parent"
    	        app:layout_constraintStart_toStartOf="parent"
    	        app:layout_constraintTop_toTopOf="parent"
    	        tools:srcCompat="@tools:sample/backgrounds/scenic" />
    	
    	    <TextView
    	        android:id="@+id/tv_description"
    	        android:layout_width="0dp"
    	        android:layout_height="wrap_content"
    	        app:layout_constraintEnd_toEndOf="parent"
    	        app:layout_constraintStart_toStartOf="parent"
    	        app:layout_constraintTop_toBottomOf="@+id/img_backgroud"
    	        android:layout_marginTop="25dp"
    	        android:textColor="@android:color/black"
    	        android:textSize="20sp"/>
    	</androidx.constraintlayout.widget.ConstraintLayout>
    

    這個類名稱的命名規則爲:XML layout文件名去掉下劃線,下劃線首字母大寫,最後加上Binding。例如我有一個layout文件叫activity_description.xml,那對應生成的類文件爲ActivityDescriptionBinding.java

    生成的類文件位於Module的build\generated\data_binding_base_class_source_out\debug\out\包名\databinding下,如下圖所示:
    在這裏插入圖片描述

  • 使用此生成類引用XML layout文件中的控件

    調用生成類ActivityDescriptionBindinginflate()方法獲得類實例對象,通過getRoot()方法可以獲得layout文件的最外層View,此例中是一個ConstraintLayout. 通過Activity的 setContentView()方法可以爲Activity設置內容。layout文件中只要是有id的view, 在這個生成類中都會對應的生成一個 public final 的屬性,例如

     <TextView
            android:id="@+id/tv_description"
            ...
            />
    

    對應的生成字段爲

      @NonNull
      public final TextView tvDescription;
    

    那就可以直接使用對象實例訪問了,如下代碼所示:

    	class DescriptionActivity : AppCompatActivity() {
    	
    		    private lateinit var  binding: ActivityDescriptionBinding
    		
    		    override fun onCreate(savedInstanceState: Bundle?) {
    		        super.onCreate(savedInstanceState)
    		        binding=ActivityDescriptionBinding.inflate(layoutInflater)
    		        setContentView(binding.root)
    		
    		        binding.tvDescription.text = "關關雎鳩,在河之洲.窈窕淑女,君子好逑."
    		        binding.tvDisplayDate?.text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
    		    }
         }
    

注意: 如果你不想把XMLlayout文件中某個含有Id的view包含到生成類中的話,就設置此view的tools:viewBindingIgnore屬性爲true

下圖演示了橫豎屏使用不同layout文件的情形
在這裏插入圖片描述

與現有方法相比較的優勢

目前Android開發中完成View映射的方法主要有 findViewByIdButterKnife, 如果使用kotlin的話還可以使用Kotlin Android Extensions

ViewBinding對比以上方法有如下幾點優勢:

  • Type safety: findViewById, ButterKnife 均存在類型轉換問題,例如不小心將一個TextView錯誤的賦值給一個Button變量,都會報錯,這一錯誤很容易出現,關鍵在錯誤還出現在運行時,而不是編譯時!

而ViewBinding中,產生的binding類中的屬性是依據XML layout文件生成的,所以類型不會錯,生成的時候已經處理好了。

  • Null safety: findViewById, ButterKnifeKotlin Android Extensions 均存在Null不安全問題。這個什麼意思呢?就是在我們訪問那個View的時候它不存在。爲什麼會出現這種情況呢?例如不小心使用了錯誤的Id,或者訪問的時候那個view還不存在。
    使用了錯誤Id這個估計大家都有此類經歷,但是訪問時候那個view不存在怎麼理解呢?例如我們在手機橫屏和豎屏的時候分別使用一套XML layout文件,假設橫屏中包含了一個豎屏中沒有的view,那麼在屏幕從橫屏旋轉到豎屏的時候,NullPointer問題就出現了。

而ViewBinding中, 產生的binding類中的屬性是依據XML layout文件生成的,所以Id不會錯。而且其將僅存在某一個配置下的layout文件的那些view對應的字段標記爲@Nullable ,例如本例中的

 @Nullable
  public final TextView tvDisplayDate;

而且,生成類中還會很貼心的給你加上詳細的註釋。這一切都是爲了提醒程序員,注意對這個view特別處理,它在某些情況下爲Null。

  • 簡潔優雅: 將綁定view的模板代碼自動生成到了其他類中,使controlor類(Activity,Fragment)更加清晰了。

什麼原理

其實通過上面的分析,估計你對其原理也猜的的八九不離十了。就是Google在那個用來編譯的gradle插件中增加了新功能,當某個module開啓ViewBinding功能後,編譯的時候就去掃描此模塊下的layout文件,生成對應的binding類。那些你所熟悉的findViewById操作都是在這個自動生成的類裏面呢,如下所示

	public final class ActivityDescriptionBinding implements ViewBinding {
			  @NonNull
			  private final ConstraintLayout rootView;
			
			  @NonNull
			  public final ImageView imgBackgroud;
			
			  @NonNull
			  public final TextView tvDescription;
			
			  /**
			   * This binding is not available in all configurations.
			   * <p>
			   * Present:
			   * <ul>
			   *   <li>layout-land/</li>
			   * </ul>
			   *
			   * Absent:
			   * <ul>
			   *   <li>layout/</li>
			   * </ul>
			   */
			  @Nullable
			  public final TextView tvDisplayDate;
			
			  private ActivityDescriptionBinding(@NonNull ConstraintLayout rootView,
			      @NonNull ImageView imgBackgroud, @NonNull TextView tvDescription,
			      @Nullable TextView tvDisplayDate) {
			    this.rootView = rootView;
			    this.imgBackgroud = imgBackgroud;
			    this.tvDescription = tvDescription;
			    this.tvDisplayDate = tvDisplayDate;
			  }
			
			  @Override
			  @NonNull
			  public ConstraintLayout getRoot() {
			    return rootView;
			  }
			
			  @NonNull
			  public static ActivityDescriptionBinding inflate(@NonNull LayoutInflater inflater) {
			    return inflate(inflater, null, false);
			  }
			
			  @NonNull
			  public static ActivityDescriptionBinding inflate(@NonNull LayoutInflater inflater,
			      @Nullable ViewGroup parent, boolean attachToParent) {
			    View root = inflater.inflate(R.layout.activity_description, parent, false);
			    if (attachToParent) {
			      parent.addView(root);
			    }
			    return bind(root);
			  }
			
			  @NonNull
			  public static ActivityDescriptionBinding bind(@NonNull View rootView) {
			    // The body of this method is generated in a way you would not otherwise write.
			    // This is done to optimize the compiled bytecode for size and performance.
			    String missingId;
			    missingId: {
			      ImageView imgBackgroud = rootView.findViewById(R.id.img_backgroud);
			      if (imgBackgroud == null) {
			        missingId = "imgBackgroud";
			        break missingId;
			      }
			
			      TextView tvDescription = rootView.findViewById(R.id.tv_description);
			      if (tvDescription == null) {
			        missingId = "tvDescription";
			        break missingId;
			      }
			
			      TextView tvDisplayDate = rootView.findViewById(R.id.tv_display_date);
			
			      return new ActivityDescriptionBinding((ConstraintLayout) rootView, imgBackgroud,
			          tvDescription, tvDisplayDate);
			    }
			    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
			  }
	}

其中核心代碼是bind(@NonNull View rootView)方法,除此之外還有兩個inflate()重載方法,一般情況下我們使用這兩個方法獲得binding類的實例。下面介紹一下這三個方法的使用場景:

  1. 在Activity中使用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        setContentView(ActivityDescriptionBinding.inflate(getLayoutInflater()).getRoot());
        ...
    }
  1. 在Fragment中使用:
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return ActivityDescriptionBinding.inflate(inflater, container, false).getRoot();
    }
  1. 在RecyclerView的ViewHolder中使用
   static class BeautyViewHolder extends RecyclerView.ViewHolder{
        private final ItemBeautyBinding binding;
        public BeautyViewHolder(@NonNull View itemView) {
            super(itemView);
            binding= ItemBeautyBinding.bind(itemView);
        }
    }

注意

	@Nullable
    public final TextView tvDisplayDate;

字段,被標記爲@Nullable了,那是因爲本例給橫屏和豎屏分別設置了一個layout文件,此view只存在於橫屏中的layout文件中. 所以在使用的時候就要注意null的情況。

如何改進

好了,文章到此也該結束了!等等,這段不是應該講如何改進嗎?讓大家失望了,因爲我也不知道如何改進,我此刻甚至都不是非常清楚那個編譯器是如何生成那個binding類的。丟人了,丟人了。。。我下去再研究一下吧

總結

讓們一起免回一下那些使用ButterKnife的日子吧!事實再一次證明平臺的強大性,就算強如ButterKnife也會在ViewBindingt推出的1年內消亡吧,現在可以明白爲什麼一個微信公衆號搞的很大時,就要考慮發展自己的App了吧,因爲你是依附於別人的平臺上,平臺規則變動對你來說就是地動山搖。

本文源碼gitbub地址: AndroidDevMemo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章