android 动态改变listview的内容
转载于:https://www.cnblogs.com/wuyou/p/3566269.html
本文模拟:点击一个按钮,为已有的listview添加一行数据
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:text="点击改变listview" android:onClick="changeListView" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout>
package com.example.listView_MultiPage; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.LinkedList; public class MyActivity extends Activity { private ListView listView; private ArrayAdapter arrayAdapter; private LinkedList<String> data = new LinkedList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView) findViewById(R.id.listview); //为listView添加数据 for(int i=0; i<5; i++) { data.add(""+i); } arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, data); listView.setAdapter(arrayAdapter); } //button控件的点击方法 public void changeListView(View view) { //先改变数据对象data data.addFirst("动态改变ListView后"); //调用adapter的通知方法告诉listview数据已经改变 arrayAdapter.notifyDataSetChanged(); } }
总结,①先改变listview数据对象的内容,②调用listview的adapter的notifyDataSetChanged()方法.