ViewStup动态加载布局
注意:ViewStub不能反复inflate,只能inflate一次,所以我们应该选择一种方式来避免重新加载布局,否则会出现错误
java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent
mainActivity.java
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import fengxing.primer.textlink.R;
public class ViewSubActivity extends AppCompatActivity implements View.OnClickListener {
private Button bt_add_layout;
private Button bt_remove_layout;
private ViewStub vs_view_sub;
private boolean isViewStubLoad = false;//ViewStub不能反复inflate,只能inflate一次
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewsub);
initView();
}
private void initView() {
bt_remove_layout = findViewById(R.id.bt_remove_layout);
bt_add_layout = findViewById(R.id.bt_add_layout);
vs_view_sub = findViewById(R.id.vs_view_sub);
bt_add_layout.setOnClickListener(this);
bt_remove_layout.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bt_remove_layout:
{
vs_view_sub.setVisibility(View.GONE);
}
break;
case R.id.bt_add_layout:
{
if (!isViewStubLoad) {
View view1 = vs_view_sub.inflate();
Button linearLayout = (Button) view;
Button button = linearLayout.findViewById(R.id.bt_new_button);
bt_add_layout.setText("新按钮");
isViewStubLoad = true;
}
}
break;
default:
break;
}
}
}
mainLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:background="@drawable/back1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ViewStub
android:layout="@layout/viewsub_next2"
android:id="@+id/vs_view_sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ViewStub>
</LinearLayout>
<Button
android:id="@+id/bt_add_layout"
android:text="动态添加布局"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:id="@+id/bt_remove_layout"
android:text="动态隐藏布局"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
subLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:background="#0111"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:text="按钮"
android:id="@+id/bt_new_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>