如何在Android上动态添加元素到ListView ?

谁能解释或建议一个教程,动态创建一个ListView在android?

以下是我的要求:

  • 我应该能够通过按下按钮动态添加新元素。
  • 应该简单到足以理解(例如,可能没有任何性能改进或convertView)

我知道关于这个话题有很多问题,但我找不到任何一个能回答我的问题。

612555 次浏览

首先在项目的res/layout/main.xml文件夹中创建一个XML布局:

<?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:id="@+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>

这是一个简单的布局,顶部有一个按钮,底部有一个列表视图。注意,ListView具有id @android:id/list,它定义了ListActivity可以使用的默认ListView

public class ListViewDemo extends ListActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();


//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;


//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;


@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}


//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
}

android.R.layout.simple_list_item_1是Android提供的默认列表项布局,您可以将此库存布局用于不复杂的事情。

listItems是一个列表,它包含ListView中显示的数据。所有的插入和删除都应该在listItems上完成;listItems中的变化应该反映在视图中。这是由ArrayAdapter<String> adapter处理的,应该使用以下命令通知它:

adapter.notifyDataSetChanged();

Adapter由3个参数实例化:context,它可以是你的activity/listactivity;个人列表项的布局;最后是列表,它是列表中显示的实际数据。

而不是

listItems.add("New Item");
adapter.notifyDataSetChanged();

您可以直接拨打

adapter.add("New Item");

首先,您必须在activity_main.xml中添加一个ListView、一个EditText和一个按钮。

现在,在ActivityMain中:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


editTxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();


// Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
// and the array that contains the data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);


// Here, you set the data in your ListView
list.setAdapter(adapter);


btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {


// this line adds the data of your EditText and puts in your array
arrayList.add(editTxt.getText().toString());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
}
});
}

这对我有用,希望我帮到你了

如果你想让ListView在AppCompatActivity而不是ListActivity中,你可以做以下事情(修改@Shardul的答案):

public class ListViewDemoActivity extends AppCompatActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();


//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;


//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;


@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list_view_demo);


if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}


adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}


//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}


protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
return mListView;
}


protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}


protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}

在你的布局中,你可以使用android:id="@+id/listDemo"而不是android:id="@android:id/list"

所以现在你可以在正常的AppCompatActivity里面有一个ListView

java文件的代码。

public class MainActivity extends Activity {


ListView listview;
Button Addbutton;
EditText GetValue;
String[] ListElements = new String[] {
"Android",
"PHP"
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


listview = (ListView) findViewById(R.id.listView1);
Addbutton = (Button) findViewById(R.id.button1);
GetValue = (EditText) findViewById(R.id.editText1);


final List < String > ListElementsArrayList = new ArrayList < String >
(Arrays.asList(ListElements));




final ArrayAdapter < String > adapter = new ArrayAdapter < String >
(MainActivity.this, android.R.layout.simple_list_item_1,
ListElementsArrayList);


listview.setAdapter(adapter);


Addbutton.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {


ListElementsArrayList.add(GetValue.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
}

activity_main.xml布局文件的代码。

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.listviewaddelementsdynamically_android_examples
.com.MainActivity" >


<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:text="ADD Values to listview" />


<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Add elements listView" />


<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true" >
</ListView>


</RelativeLayout>

截图

enter image description here

简单的回答:当你创建一个ListView时,你传递给它一个数据引用。 现在,无论何时该数据将被更改,它都会影响列表视图,因此在调用adapter.notifyDataSetChanged();.

之后,它将向列表视图中添加该项

如果你正在使用RecyclerView,只更新最后一个元素(如果你已经在objs列表的末尾添加了它)来节省内存:

        This is the simple answer how to add datas dynamically in listview android kotlin




class MainActivity : AppCompatActivity(){
        

var listItems = arrayListOf<String>()
val array = arrayOf("a","b","c","d","e")
var listView: ListView? = null
    

private lateinit var adapter: listViewAdapter
        

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.scrollview_layout)
        

listItems.add("a")
listItems.add("b")
listItems.add("c")
listItems.add("d")
listItems.add("e")
        

//if you want to add array items to a list you can try this for each loop
for(items in array)
listItems.add(items)
                

//check the result in console
Log.e("TAG","listItems array: $listItems")
    

adapter = ListViewAdapter()
adapter.updateList(listItems)
adapter.notifyDataSetChanged()
        

}
}




//Here is the adapter class
class ListviewAdapter : BaseAdapter(){
    

private var itemsList = arrayListOf<String>()
    

override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
var view  = container
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
if (view == null)
view = inflater.inflate(R.layout.list_pc_summary, parent, false)
    

return view
}
    

override fun getItem(position: Int): Any  = itemsList[position]
    

override fun getItemId(position: Int): Long = position.toLong()
    

override fun getCount(): Int = itemsList.size
    

fun updateList(listItems: ArrayList<String>()){
this.itemsList = listItems
notifyDatSetChanged
    

}
   

}
       

//Here I just explained two ways, we can do this many ways.