我每按一次按钮就会添加一个列表项。我有这个代码,但它只是第一次添加一个列表项。我怎样才能使它每次单击按钮时都添加一个。或者甚至可能是特定的时间范围?
在课堂上声明变量。
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems = new ArrayList<>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapterForPic;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;
在onCreate()中初始化。
if (mListView == null) {
mListView = (ListView) findViewById(R.id.photosListView);
}
adapterForPic=new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapterForPic);
进行插入的方法。
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter);
adapterForPic.notifyDataSetChanged();
clickCounter++;
}
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.photosListView);
}
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;
}
}
答案 0 :(得分:0)
我的问题在于ListView元素的高度。它是wrap_content
,因此只显示了一个列表项。