他们可以放入一个布局文件并单独充气吗?
没有。当您扩充布局资源时,您正在扩充该文件中的所有内容。
会根据不同的条件创建(膨胀)不同的视图组件(例如 Button、TextView)。
听起来你可以通过使用ViewStub tags来实现你想要的。
为此,您可以照常创建主布局文件。但是,在您想要拥有动态内容的任何地方,您都可以添加<ViewStub> 标记。然后,在 Java/Kotlin 中,膨胀主布局后,您可以将不同的视图膨胀到 ViewStub 中。
<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="Header"/>
<ViewStub
android:id="@+id/stub"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Footer"/>
</LinearLayout>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLICK ME">
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Can't click me">
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ViewStub stub = findViewById(R.id.stub);
if (isUseButton) {
stub.setLayoutResource(R.layout.button);
} else {
stub.setLayoutResource(R.layout.text);
}
stub.inflate();
}