Update the data in the Adapter and notify the ListView to display

Click the button on the interface to call the notifyDatasetChanged() method of the Adapter to notify the ListView to update the display. 
Example: 
Java code   Favorite code
  1. package  com.laili.apater;  
  2.   
  3. import java.util.ArrayList;   
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.ArrayAdapter;  
  8. import android.widget.Button;  
  9. import android.widget.ListView;  
  10.   
  11. public class ListAdapterActivity extends Activity {  
  12.      
  13.     private ListView list;  
  14.     private ArrayAdapter<String> adapter;  
  15.     private ArrayList<String> data;  
  16.     private Button addBtn;  
  17.     private int i = 0;  
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super .onCreate (savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.           
  23.         list = (ListView) findViewById(R.id.list);  
  24.         data = new ArrayList<String>();  
  25.         for (i = 0; i < 5; i++) {  
  26.             data.add(new String("" + (i + 1)));  
  27.         }  
  28.           
  29.         adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);  
  30.         list.setAdapter(adapter);  
  31.           
  32.           
  33.         addBtn = (Button) findViewById(R.id.add);  
  34.         addBtn.setOnClickListener(new View.OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(View v) {  
  38.                 System.out.println(i);  
  39.                 data.add(new String("" + (++i)));  
  40.                 System.out.println(i);  
  41.                 adapter.notifyDataSetChanged();  
  42.             }  
  43.         });  
  44.           
  45.     }  
  46. }  

layout: 
Java code   Favorite code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.     <ListView   
  12.         android:id="@+id/list"  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_weight="1"/>  
  16.     <Button   
  17.         android:id="@+id/add"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="添加"/>  
  21. </LinearLayout>  

display effect: 
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326877045&siteId=291194637