Java和Kotlin中的ViewStub用法区别
XML布局如下:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ViewStub
android:id="@+id/viewStub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/viewstub_test"/>
</LinearLayout>
ViewStub viewstub_test的布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<TextView
android:id="@+id/tv_title"
android:text="HelloWorld"
android:textSize="36sp"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
在Java中ViewStub的用法如下:
//需要先找到ViewStub
ViewStub vs = (ViewStub)findViewById(R.id.viewStub)
//或者直接设置Visiable vs.setVisibility(View.VISIBLE);
LinearLayout layout = (LinearLayout)vs.inflate()
//找到ViewStub里面的view
TextView tv = layout.findViewById(R.id.tv_title)
tv.setText("你好~")
在Kotlin中ViewStub的用法如下:
//viewStub.inflate()
viewStub.visibility = View.VISIBLE
//不需要再次findViewById 可以直接调用
//TextView tv = layout.findViewById<TextView>(R.id.tv_title)
tv_title.text = "你好"