如何使用notifyDatasetChanged()来使用ListAdapter?

现在我使用setAdapter来更新我的ListView,但我认为正确的方法是使用notifiyDatasetChanged()并且我无法在我的主类中工作(它在适配器中)。 这是错误:

对于ListAdaptertypes,方法notifyDatasetChanged()未定义

我猜这有更好的方法 – 有人能指出我正确的方向吗?

这是我的代码的相关部分:

public class ScoreList extends SherlockFragmentActivity { private ListView listViewScore; static List listScore = new ArrayList(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.score_list); ctx = this; listScore = dbh.getAllScores(); listViewScore = (ListView) findViewById(R.id.score_list); listViewScore.setAdapter(new ScoreListAdapter(ctx, R.layout.score_row_item, listScore)); listViewScore.getAdapter().notifyDatasetChanged(); //this is where I get the error } } 

这是适配器:

 public class ScoreListAdapter extends ArrayAdapter { private int resource; private LayoutInflater inflater; public ScoreListAdapter(Context ctx, int resourceId, List objects) { super(ctx, resourceId, objects); resource = resourceId; inflater = LayoutInflater.from(ctx); //context = ctx; } @Override public View getView(final int position, View convertView, ViewGroup parent) { convertView = (LinearLayout) inflater.inflate(resource, null); Score score = getItem(position); TextView txtName = (TextView) convertView.findViewById(R.id.name); txtName.setText(score.getName()); TextView txtScoreChange = (TextView) convertView .findViewById(R.id.scoreChange); int scoreChange = Integer.parseInt(score.getScoreChange()); if (scoreChange > 0) txtScoreChange.setText("+" + scoreChange); else if (scoreChange < 0) txtScoreChange.setText("" + scoreChange); else txtScoreChange.setText(""); TextView txtScoreTotal = (TextView) convertView .findViewById(R.id.scoreTotal); txtScoreTotal.setText(score.getScoreTotal()); final LinearLayout currentRow = (LinearLayout) convertView .findViewById(R.id.scoreRowLayout); notifyDataSetChanged(); return convertView; } } 

创建自定义适配器的实例,以便您可以随意使用它…

 public class ScoreList extends SherlockFragmentActivity { private ListView listViewScore; private ScoreListAdapter adapter; static List listScore = new ArrayList(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.score_list); ctx = this; listScore = dbh.getAllScores(); listViewScore = (ListView) findViewById(R.id.score_list); adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore); listViewScore.setAdapter(adapter); adapter.notifyDatasetChanged(); } } 

顺便说一句,如果您的listScore数组已经加载,那么您不需要使用

 adapter.notifyDatasetChanged(); 

不要调用notifyDataSetChanged(); 创造时的方法。

只有当listViewScore的内容发生变化时才会调用它,并在此时使用它 –

更换

 listView.getAdapter().notifyDatasetChanged(); 

 ((ScoreListAdapter)listView.getAdapter()).notifyDataSetChanged(); 

并看到魔术……

谢谢。