How to remove all items from ListView in Android Studio
How to remove all items from ListView in Android Studio
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#d6b65d"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove All Items From ListView"
/>
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn"
/>
</RelativeLayout>
MainActivity.java
package com.cfsuman.me.androidcodesnippets;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference of widgets from XML layout
final ListView lv = (ListView) findViewById(R.id.lv);
final Button btn = (Button) findViewById(R.id.btn);
// Initializing a new String Array
String[] fruits = new String[] {
"Black Walnut",
"Blackberry",
"Blue tongue",
"Bolwarra",
"Bottle Gourd"
};
// Create a List from String Array elements
final List<String> fruits_list = new ArrayList<String>(Arrays.asList(fruits));
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, fruits_list);
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Remove / Delete all items from List
// Clear ListView Items
fruits_list.clear();
/*
notifyDataSetChanged ()
Notifies the attached observers that the underlying
data has been changed and any View reflecting the
data set should refresh itself.
*/
arrayAdapter.notifyDataSetChanged();
}
});
}
}
No comments
Post a Comment