LinearLayout提供了幾個方法,用作動態添加View特別好用;
可以添加View、刪除View、刪除指定位置View、刪除全部View;
看代碼:
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
LinearLayout ll;
private LayoutInflater mInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mInflater = LayoutInflater.from(this);
ll = findViewById(R.id.ll);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "add", Toast.LENGTH_SHORT).show();
ll.addView(View.inflate(MainActivity.this, R.layout.item, null)); //添加一個View
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "delect", Toast.LENGTH_SHORT).show();
ll.removeViewAt(1); //刪除指定位置的View
// ll.removeView(view); //刪除指定View
}
});
findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "delectAll", Toast.LENGTH_SHORT).show();
ll.removeAllViews(); //刪除全部View
}
});
}
}
Xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/ll"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn1"
android:text="添加"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn2"
android:text="刪除"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn3"
android:text="清空"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</ScrollView>
添加的View:
<?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="wrap_content">
<TextView
android:id="@+id/tv"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>