gpt4 book ai didi

java - 如何让 notifyDatasetChanged() 与 ListAdapter 一起工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:47:50 24 4
gpt4 key购买 nike

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

未为类型 ListAdapter 定义方法 notifyDatasetChanged()

我猜有更好的方法可以做到这一点 - 谁能给我指出正确的方向?

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

public class ScoreList extends SherlockFragmentActivity {

private ListView listViewScore;

static List<Score> listScore = new ArrayList<Score>();
@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<Score> {
private int resource;
private LayoutInflater inflater;

public ScoreListAdapter(Context ctx, int resourceId, List<Score> 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<Score> listScore = new ArrayList<Score>();
@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(); 

关于java - 如何让 notifyDatasetChanged() 与 ListAdapter 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14859766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com