我有一个 ListView ,在刷新它并获取新数据后。它转到 ListView 的顶部,而不是我上次滚动到的位置。
我设置了一个计时器,在 2 秒后,它会获取新数据并将其放入 ListView 中。
如有任何帮助,我们将不胜感激。提前致谢:D
这是主要 Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
handler.postDelayed(runnable, 3500);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
getJSON();
handler.postDelayed(this, 2000);
}
};
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String name = jo.getString(Config.TAG_NAME);
HashMap<String,String> employees = new HashMap<>();
employees.put(Config.TAG_ID,id);
employees.put(Config.TAG_NAME,name);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_NAME},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSON_STRING = s;
showEmployee();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
最佳答案
在 onCreate() 中用空列表初始化您的适配器并与 listView 绑定(bind)。 使您的适配器和列表在类里面成为全局。
现在无论何时向适配器添加数据,只需调用 adapter.notifyDataSetChanged()
这也是它在 fragment 中的工作方式。
关于android - 获取新数据后保持 ListView 的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432209/