0
我正在建立一個用戶界面,我在其中使用ListView來保存用戶提出的問題的數據。每當用戶創建新問題時,我都會嘗試更新列表視圖。現在的問題是數據更新但不是馬上。添加問題後,我需要導航到另一個屏幕,然後回來查看更新的列表。這也造成我想解決一些其他問題(佈局沒有得到正確顯示) 這是我的活動代碼:Android ListView沒有刷新馬上使用notifyDataSetChanged
public class QuestionsScreen extends Activity {
.....
.....
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions_screen);
.....
questions=new ArrayList<String>();
qId=new ArrayList<Integer>();
.....
.....
//building API
resourceApi = ApiBuilder.getResourceApi(token);
// calling API function to get questions from db
resourceApi.listQuestions(groupId, new Callback<List<Question>>(){
@Override
public void failure(RetrofitError arg0) {
// TODO Auto-generated method stub
}
@Override
public void success(List<Question> arg0, Response arg1) {
// TODO Auto-generated method stub
for(Question q:arg0)
{
questions.add(q.getTitle());
qId.add(q.getId());
}
}
});
adapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,questions);
lv.setAdapter(adapter);
.....
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View x;
x = inflater.inflate(R.layout.groupdialog, null);
dialog.setView(x);
dialog.setTitle("Add question");
TextView t= (TextView)x.findViewById(R.id.dialogTv);
t.setText("Please type in the question");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int which) {
// TODO Auto-generated method stub
name = (EditText) x.findViewById(R.id.dialog_groupName);
out = name.getText().toString();
addQuestion();
d.dismiss();
}
});
dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int which) {
// TODO Auto-generated method stub
d.cancel();
}
});
alert = dialog.create();
//button to ask a new question
newQ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
alert.show();
}
});
}
這是被稱爲當「添加新問題」功能按鈕被按下:
public void addQuestion()
{
resourceApi.createQuestion(groupId, out, new Callback<Question>(){
@Override
public void failure(RetrofitError err) {
// TODO Auto-generated method stub
}
@Override
public void success(Question q, Response response) {
// TODO Auto-generated method stub
// adapter.add(q.getTitle());
questions.add(q.getTitle());
qId.add(q.getId());
}
});
adapter.notifyDataSetChanged();
Toast.makeText(QuestionsScreen.this, "New Question created",Toast.LENGTH_LONG).show();
}
顯示吐司。但是,列表視圖不會隨新問題而更新。我嘗試使用adapter.add()以及它只是導致一些其他問題,所以我不想使用它。 任何人都可以提出一個更好的方法或指出我做錯了什麼?
謝謝,這似乎工作! (y)的 – leMS