Android的 - 添加和使用ArrayAdapter一次显示项目的ListView一个
-
22-09-2019 - |
题
我使用的是ArrayAdapter将项目添加到自定义的ListView和显示在我的Android应用程序的结果。我遇到的问题是,一个ArrayAdapter似乎要等到所有项目都在上面则显示视图之前。这就是说,当我加入的项目,以一个ArrayAdapter和我打电话notifyDataSetChanged,它不更新ListView控件来显示添加的项目。它等待,直到所有的数据项都表示项目之前加入GetView被调用。
我想什么它做的是将它添加到ListView之后立即显示该项目。这是可能的?
相信相关的代码如下:
r_adapter = new ReminderAdapater(Activity_ContentSearch.this, R.layout.search_listitem, myList);
listView.setAdapter(r_adapter);
...
r_adapter.notifyDataSetChanged();
r_adapter.clear();
for(int i = 0; i < myList.size(); i++)
{
r_adapter.add(myList.get(i));
r_adapter.notifyDataSetChanged();
}
正如你所看到的,即使我add方法调用后notifyDataSetChanged,它实际上并没有更新的观点。它已完成上述循环的观点是最后更新后(根据我所知道的,那是因为GetView不叫,直到此部分代码完成后)。
我试图重写我的自定义ArrayAdapter的添加方法,没有运气,因为我没有访问该方法中的视图。
任何帮助将受到欢迎:)
巴拉
解决方案
Android的UI是单线程。你是不是每次添加到适配器的进入时间给从主应用程序线程控制返回到Android系统。因此,Android不得到一个机会,直到返回控制,以显示你的条目,你不这样做,直到你的全部人口您的适配器。
这里是表示使用的一个例子 AsyncTask
逐步填满一个ArrayAdapter
通过后台线程。
/***
Copyright (c) 2008-2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.async;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
public class AsyncDemo extends ListActivity {
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet", "consectetuer",
"adipiscing", "elit", "morbi",
"vel", "ligula", "vitae",
"arcu", "aliquet", "mollis",
"etiam", "vel", "erat",
"placerat", "ante",
"porttitor", "sodales",
"pellentesque", "augue",
"purus"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new ArrayList<String>()));
new AddStringTask().execute();
}
class AddStringTask extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}
return(null);
}
@SuppressWarnings("unchecked")
@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter<String>)getListAdapter()).add(item[0]);
}
@Override
protected void onPostExecute(Void unused) {
Toast
.makeText(AsyncDemo.this, "Done!", Toast.LENGTH_SHORT)
.show();
}
}
}
不隶属于 StackOverflow