我制作了一个应用程序,该应用程序从两个文本文件中获取单词和定义(一个带有单词,另一个带有定义)。随机数用于生成要显示的单词,然后随机排列5个定义以及正确的选项以显示选项。该应用程序运行正常,但是单击任何选项时,都不会为下一个单词用新选项刷新该选项。
ListView list;
ArrayAdapter<String> adap;
ArrayList<String> word=new ArrayList<>();
List<String> dfn=new ArrayList<>();
List<String> dfn2=new ArrayList<>();
String que="",ans="";
int counter=0;
private void random(){
Random num = new Random();
int nw = num.nextInt(word.size());
que = word.get(nw);
ans = dfn2.get(nw);
dfn = dfn2;
dfn.remove(ans);
Collections.shuffle(dfn);
dfn = dfn.subList(0,4);
dfn.add(ans);
Collections.shuffle(dfn);
list = (ListView) findViewById(R.id.li);
adap = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
dfn
);
TextView t = (TextView) findViewById(R.id.t);
t.setText(que);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
TextView t2 = (TextView) findViewById(R.id.t2);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Scanner sc = new Scanner(getResources().openRawResource(R.raw.word2));
Scanner sc2 = new Scanner(getResources().openRawResource(R.raw.def2));
while(sc.hasNextLine()&&sc2.hasNextLine()){
String a = sc.nextLine();
String b = sc2.nextLine();
word.add(a);
dfn.add(b);
dfn2.add(b);
}
sc.close();
sc2.close();
random();
run();
}
public void run(){
list.setAdapter(adap);
list.setOnItemClickListener((adapterView, view,i,l)->{//lambda expression
if(dfn.get(i).equals(ans)){
Toast.makeText(getApplicationContext(),"Correct!",Toast.LENGTH_SHORT).show();
counter++;
}
else{
Toast.makeText(getApplicationContext(),"Wrong!",Toast.LENGTH_SHORT).show();
}
TextView t2 = (TextView) findViewById(R.id.t2);
t2.setText("Score : "+counter);
notifyDataChanged();
}
);
}
public void notifyDataChanged() {
random();
adap.notifyDataSetChanged();
}
}
我希望每次单击后都用新选项替换
答案 0 :(得分:0)
您确实会在每次单击时创建一个新适配器,但是没有将新适配器设置为列表。
您应该只更新值,而不是每次都创建一个新适配器。只是在这种情况下,您还必须调用notifyDataSetChanged(已经执行但不必执行的操作)
if (adapt == null) {
adap = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
dfn
);
} else {
adapt.updateItems(dfn);
adap.notifyDataSetChanged();
}
public void notifyDataChanged() {
random();
}