最近斷斷續續地把項目的界面部分的代碼由JAva改爲了Kotlin編寫,而且若是應用了kotlin-android-extensions
插件,一個顯而易見的好處是不再用寫 findViewById()
來實例化你的控件對象了,直接操做你在佈局文件裏的id便可,這一點我感受比butterknife
作的還簡潔友好。html
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"
}
}
複製代碼
其中kotlinx.android.synthetic.main.activity_main.*
是kotlin-android-extensions
插件自動生成的。下面咱們來解析下原理。由於kotlin也是一門JVM語言,最近也會和java同樣編譯成class字節碼,因此咱們直接來反編譯看看生成的java文件。java
選擇Decompile
,解析出來的代碼以下android
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()
進行查找。git
再來看下Fragment
中的使用:github
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()源碼bash
@Nullable
public View getView() {
return this.mView;
}
複製代碼
再看下mView成員變量的賦值時機:app
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()
方法裏使用。ide
除了Activity
和Fragment
,咱們用的最多的UI佈局當屬Adapter了,kotlin-android-extensions
也提供了對這一類動態佈局的支持。由於這一功能是實現性質的,默認關閉,咱們須要手動打開,在build.gradle
中開啓:佈局
androidExtensions {
experimental = true
}
複製代碼
而後再recycler.adapter中使用以下:
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_recyclerview.*
class MyAdapter(val context: Context, val data: List<String>) :
RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_recyclerview, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.name_tv.text = data[position]
holder.itemView.setOnClickListener {
Toast.makeText(context,"點擊了第$position 項",Toast.LENGTH_SHORT).show()
}
}
override fun getItemCount(): Int {
return data.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), LayoutContainer {
override val containerView: View = itemView
}
}
複製代碼
能夠看到相比Activity
和Fragment
,咱們的ViewHolder
須要多實現一個接口LayoutContainer
。看下它的源碼:
/** * A base interface for all view holders supporting Android Extensions-style view access. */
public interface LayoutContainer {
/** Returns the root holder view. */
public val containerView: View?
}
複製代碼
只有一個對象,咱們須要設置這個值,用來手動指定root holder view
,也就是ViewHolder
的itemView
。反編譯看下ViewHolder
生成的java代碼就好理解了,此處的getContainerView
做用至關於Fragment的getView()
,只不過Fragment
自帶了這個獲取佈局根View的方法,而Adapter須要再去經過LayoutContainer
接口實現而已。
public final class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder implements LayoutContainer {
@NotNull
private final View containerView;
private HashMap _$_findViewCache;
@NotNull
public View getContainerView() {
return this.containerView;
}
public ViewHolder(@NotNull View itemView) {
Intrinsics.checkParameterIsNotNull(itemView, "itemView");
super(itemView);
this.containerView = itemView;
}
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.getContainerView();
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();
}
}
}
複製代碼