使用ViewGroup.addView(View)可动态添加部件,ViewGroup.removeAllViews()用于移除所有部件
示例如下
MainActivity.java
package com.bu_ish.add_view_test; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity { private LinearLayout llWidgets; private Button btnAddWidgets, btnClearWidgets; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); llWidgets = findViewById(R.id.llWidgets); btnAddWidgets = findViewById(R.id.btnAddWidgets); btnClearWidgets = findViewById(R.id.btnClearWidgets); btnAddWidgets.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int total = new Random().nextInt(10) + 1; for (int i = 0; i < total; ++i) { Button btn = new Button(MainActivity.this); btn.setText("按钮" + (i + 1)); TextView tv = new TextView(MainActivity.this); tv.setText("文本视图" + (i + 1)); LinearLayout ll = new LinearLayout(MainActivity.this); ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.addView(btn); ll.addView(tv); llWidgets.addView(ll); } } }); btnClearWidgets.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { llWidgets.removeAllViews(); } }); } }