0
我正在做一个按钮来添加一个列表项,每次我点击它。我有这个代码,但它只是第一次添加一个列表项。我怎样才能让它每次点击按钮时都增加一个。或者甚至可能是特定的时间范围?这段代码为什么只添加一个列表项目一次?
类中变量的声明。
//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;
}
}
我用'ListView'和'Button'创建了一个简单的活动,并将代码复制到它中。我删除了'getListAdapter()',因为它从未在您发布的代码中调用过。每次点击按钮时,我的应用程序都会正确地继续添加视图,这让我认为问题出现在您*未发布的代码中;你可以发布一切从你的活动/布局,而不是只是件? –
[This](https://codeshare.io/adkV0B)是我在Post.java文件中完整的Java代码。 [这里](https://codeshare.io/al41Pm)是我的布局文件。 –
这个建议是基于我过去见过的一些奇怪的行为。尝试更改“listItems.add(”Clicked:“+ clickCounter);”到“listItems.add(”Clicked:“+ String.valueOf(clickCounter));” – Hahn