Kotlin直接使用控制元件ID原理解析
阿新 • • 發佈:2018-12-16
最近斷斷續續地把專案的介面部分的程式碼由JAva改成了Kotlin編寫,並且如果應用了kotlin-android-extensions
外掛,一個顯而易見的好處是再也不用寫 findViewById()
來例項化你的控制元件物件了,直接操作你在佈局檔案裡的id即可,這一點我感覺比butterknife
做的還簡潔友好。
Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textview.text="hello world"
}
}
複製程式碼
下面我們來解析下原理。因為kotlin也是一門JVM語言,最近也會和java一樣編譯成class位元組碼,所以我們直接來反編譯看看生成的java檔案。
選擇Decompile
,解析出來的程式碼如下
public final class MainActivity extends AppCompatActivity {
private HashMap _$_findViewCache;
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this .setContentView(2131296284);
TextView var10000 = (TextView)this._$_findCachedViewById(id.textview);
Intrinsics.checkExpressionValueIsNotNull(var10000, "textview");
var10000.setText((CharSequence)"hello world");
}
public View _$_findCachedViewById(int var1) {
if (this._$_findViewCache == null ) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(var1);
if (var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(var1, var2);
}
return var2;
}
public void _$_clearFindViewByIdCache() {
if (this._$_findViewCache != null) {
this._$_findViewCache.clear();
}
}
}
複製程式碼
可以很清楚看到最終還是呼叫了findViewById()
,不過獲取View物件直接呼叫的是findCachedViewById
,並且建立一個 HashMap 進行View物件的快取,避免每次呼叫 View 時都會重新呼叫findViewById()
進行查詢。
Fragment
再來看下Fragment
中的使用:
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_blank.*
class BlankFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_blank, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
textview_fra.text="hello world"
}
}
複製程式碼
反編譯後代碼如下
public final class BlankFragment extends Fragment {
private HashMap _$_findViewCache;
@Nullable
public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Intrinsics.checkParameterIsNotNull(inflater, "inflater");
return inflater.inflate(2131296285, container, false);
}
public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
Intrinsics.checkParameterIsNotNull(view, "view");
super.onViewCreated(view, savedInstanceState);
TextView var10000 = (TextView)this._$_findCachedViewById(id.textview_fra);
Intrinsics.checkExpressionValueIsNotNull(var10000, "textview_fra");
var10000.setText((CharSequence)"hello world");
}
public View _$_findCachedViewById(int var1) {
if (this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(var1);
if (var2 == null) {
View var10000 = this.getView();
if (var10000 == null) {
return null;
}
var2 = var10000.findViewById(var1);
this._$_findViewCache.put(var1, var2);
}
return var2;
}
public void _$_clearFindViewByIdCache() {
if (this._$_findViewCache != null) {
this._$_findViewCache.clear();
}
}
// $FF: synthetic method
public void onDestroyView() {
super.onDestroyView();
this._$_clearFindViewByIdCache();
}
}
複製程式碼
可以看到最終是通過呼叫getView().findViewById()
來進行控制元件的例項化。 看下getView()原始碼
@Nullable
public View getView() {
return this.mView;
}
複製程式碼
再看下mView成員變數的賦值時機:
void performCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (this.mChildFragmentManager != null) {
this.mChildFragmentManager.noteStateNotSaved();
}
this.mPerformedCreateView = true;
this.mViewLifecycleOwner = new LifecycleOwner() {
public Lifecycle getLifecycle() {
if (Fragment.this.mViewLifecycleRegistry == null) {
Fragment.this.mViewLifecycleRegistry = new LifecycleRegistry(Fragment.this.mViewLifecycleOwner);
}
return Fragment.this.mViewLifecycleRegistry;
}
};
this.mViewLifecycleRegistry = null;
this.mView = this.onCreateView(inflater, container, savedInstanceState);
if (this.mView != null) {
this.mViewLifecycleOwner.getLifecycle();
this.mViewLifecycleOwnerLiveData.setValue(this.mViewLifecycleOwner);
} else {
if (this.mViewLifecycleRegistry != null) {
throw new IllegalStateException("Called getViewLifecycleOwner() but onCreateView() returned null");
}
this.mViewLifecycleOwner = null;
}
}
複製程式碼
可以看到mView
其實就是onCreateView()
的返回值,所以我們不能在onCreateView()
方法裡操作控制元件ID的方式操作View物件,會產生空指標異常。建議在onViewCreated()
方法裡使用。
其他
比較遺憾的是kotlin-android-extensions
貌似還不支援各種Adapter等動態佈局內的直接使用控制元件ID方法。