Update the data in the Adapter and notify the ListView to display
Others
2022-05-25 14:43:44
views: 0
Click the button on the interface to call the notifyDatasetChanged() method of the Adapter to notify the ListView to update the display.
Example:
- package com.laili.apater;
-
- import java.util.ArrayList;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
-
- public class ListAdapterActivity extends Activity {
-
- private ListView list;
- private ArrayAdapter<String> adapter;
- private ArrayList<String> data;
- private Button addBtn;
- private int i = 0;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super .onCreate (savedInstanceState);
- setContentView(R.layout.main);
-
- list = (ListView) findViewById(R.id.list);
- data = new ArrayList<String>();
- for (i = 0; i < 5; i++) {
- data.add(new String("" + (i + 1)));
- }
-
- adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
- list.setAdapter(adapter);
-
-
- addBtn = (Button) findViewById(R.id.add);
- addBtn.setOnClickListener(new View.OnClickListener() {
-
- @Override
- public void onClick(View v) {
- System.out.println(i);
- data.add(new String("" + (++i)));
- System.out.println(i);
- adapter.notifyDataSetChanged();
- }
- });
-
- }
- }
layout:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- <ListView
- android:id="@+id/list"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- <Button
- android:id="@+id/add"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="添加"/>
- </LinearLayout>
display effect:
|
Origin http://10.200.1.11:23101/article/api/json?id=326877045&siteId=291194637