Android ViewStub延迟初始化加载布局View,Kotlin
activity_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello" />
<ViewStub
android:id="@+id/my_view_stub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/my_long_time_view" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="world" />
</LinearLayout>
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewStub
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MyActivity : AppCompatActivity() {
companion object {
const val TAG = "fly/MyActivity"
}
private var mViewStub: ViewStub? = null
private var mMyLongTimeView: MyLongTimeView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "setContentView开始...")
setContentView(R.layout.activity_my)
Log.d(TAG, "setContentView结束")
mViewStub = findViewById(R.id.my_view_stub)
lifecycleScope.launch(Dispatchers.IO) {
delay(2000)
withContext(Dispatchers.Main) {
showViewStub()
}
delay(2000)
withContext(Dispatchers.Main) {
hideViewStub()
}
}
}
private fun showViewStub() {
val t = System.currentTimeMillis()
Log.d(TAG, "ViewStub inflate")
val inflatedView = mViewStub?.inflate()
//mViewStub?.visibility = View.INVISIBLE
Log.d(TAG, "inflatedView 耗时=${System.currentTimeMillis() - t}")
mMyLongTimeView = inflatedView?.findViewById(R.id.my_longt_time_view)!!
mMyLongTimeView?.setImageResource(R.mipmap.image)
}
private fun hideViewStub() {
mViewStub?.visibility = View.INVISIBLE
}
}
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatImageView
class MyLongTimeView : AppCompatImageView {
companion object {
const val TAG = "fly/MyLongTimeView"
}
constructor(ctx: Context, attribute: AttributeSet) : super(ctx, attribute) {
Log.d(TAG, "开始耗时...")
Thread.sleep(5000)
Log.d(TAG, "耗时结束")
}
}
my_long_time_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.MyLongTimeView
android:id="@+id/my_longt_time_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
</LinearLayout>
启动后就可以看到TextView的hello,world显示出来,随后显示图片,再随后隐藏图片。