Kotlin如何直接使用控件ID原理詳析
前言
最近斷斷續(xù)續(xù)地把項(xiàng)目的界面部分的代碼由JAva改成了Kotlin編寫(xiě),并且如果應(yīng)用了kotlin-android-extensions插件,一個(gè)顯而易見(jiàn)的好處是再也不用寫(xiě) findViewById()來(lái)實(shí)例化你的控件對(duì)象了,直接操作你在布局文件里的id即可,這一點(diǎn)我感覺(jué)比butterknife做的還簡(jiǎn)潔友好。
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"
}
}
其中kotlinx.android.synthetic.main.activity_main.*是kotlin-android-extensions插件自動(dòng)生成的。下面我們來(lái)解析下原理。因?yàn)閗otlin也是一門(mén)JVM語(yǔ)言,最近也會(huì)和java一樣編譯成class字節(jié)碼,所以我們直接來(lái)反編譯看看生成的java文件。

選擇Decompile,解析出來(lái)的代碼如下
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();
}
}
}
可以很清楚看到最終還是調(diào)用了findViewById() ,不過(guò)獲取View對(duì)象直接調(diào)用的是findCachedViewById,并且創(chuàng)建一個(gè) HashMap 進(jìn)行View對(duì)象的緩存,避免每次調(diào)用 View 時(shí)都會(huì)重新調(diào)用findViewById()進(jìn)行查找。
Fragment
再來(lái)看下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();
}
}
可以看到最終是通過(guò)調(diào)用getView().findViewById()來(lái)進(jìn)行控件的實(shí)例化。
看下getView()源碼
@Nullable
public View getView() {
return this.mView;
}
再看下mView成員變量的賦值時(shí)機(jī):
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其實(shí)就是onCreateView()的返回值,所以我們不能在onCreateView()方法里操作控件ID的方式操作View對(duì)象,會(huì)產(chǎn)生空指針異常。建議在onViewCreated()方法里使用。
其他(動(dòng)態(tài)布局)
除了Activity和Fragment,我們用的最多的UI布局當(dāng)屬Adapter了,kotlin-android-extensions也提供了對(duì)這一類(lèi)動(dòng)態(tài)布局的支持。因?yàn)檫@一功能是實(shí)現(xiàn)性質(zhì)的,默認(rèn)關(guān)閉,我們需要手動(dòng)打開(kāi),在build.gradle中開(kāi)啟:
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,"點(diǎn)擊了第$position 項(xiàng)",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需要多實(shí)現(xiàn)一個(gè)接口LayoutContainer??聪滤脑创a:
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();
}
}
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Android實(shí)現(xiàn)購(gòu)物車(chē)整體頁(yè)面邏輯詳解
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)購(gòu)物車(chē)的整體頁(yè)面邏輯,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
Android 中TextView的使用imageview被壓縮問(wèn)題解決辦法
這篇文章主要介紹了Android 中TextView的使用imageview被壓縮問(wèn)題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-04-04
Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實(shí)例
下面小編就為大家分享一篇Android封裝Okhttp+Retrofit+RxJava,外加攔截器實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
詳解Android.activity銷(xiāo)毀流程的工作原理
這篇文章主要介紹了詳解Activity銷(xiāo)毀流程的工作原理,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Android微信自動(dòng)搶紅包插件優(yōu)化和實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了Android微信自動(dòng)搶紅包插件優(yōu)化和實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
Android提高之SurfaceView與多線程的混搭實(shí)例
這篇文章主要介紹了Android提高之SurfaceView與多線程的混搭,很實(shí)用的功能,需要的朋友可以參考下2014-08-08
Android熱更新開(kāi)源項(xiàng)目Tinker集成實(shí)踐總結(jié)
最近項(xiàng)目集成了Tinker,開(kāi)始認(rèn)為集成會(huì)比較簡(jiǎn)單,但是在實(shí)際操作的過(guò)程中還是遇到了一些問(wèn)題,本文就會(huì)介紹在集成過(guò)程大家基本會(huì)遇到的主要問(wèn)題。下面跟著小編一起來(lái)看下吧2017-01-01
Android實(shí)現(xiàn)城市選擇三級(jí)聯(lián)動(dòng)
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)城市選擇三級(jí)聯(lián)動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12
android開(kāi)發(fā)之listView組件用法實(shí)例簡(jiǎn)析
這篇文章主要介紹了android開(kāi)發(fā)之listView組件用法,結(jié)合實(shí)例形式簡(jiǎn)單分析了listView組件的相關(guān)屬性與使用技巧,需要的朋友可以參考下2016-01-01

