Collections.shuffle(list) 打亂順序後,onItemClick 中用 ((TextView)view).getText() 比對字串決定開啟哪個 Activity,不可靠且效能差。
ListView lv = getListView();
lv.setOnItemClickListener((parent, view, position, id) -> {
String item = bands.get(position); // 直接從資料源取得當前位置項目
if ("Band0".equals(item)) {
Intent i = new Intent(Bands.this, AudioActivity.class);
i.putExtra("Band", 0);
startActivity(i);
} else if ("Band1".equals(item)) { ... }
});
class BandItem {
String name;
Class> targetActivity;
int bandIndex;
}
// 建構資料
List bands = Arrays.asList(
new BandItem("Band0", AudioActivity.class, 0),
new BandItem("Band1", VideoActivity.class, 1),
...
);
// 點擊處理
lv.setOnItemClickListener((parent, view, position, id) -> {
BandItem item = bands.get(position);
Intent i = new Intent(Bands.this, item.targetActivity);
i.putExtra("Band", item.bandIndex);
startActivity(i);
});
Collections.shuffle 只影響列表順序,資料模型綁定的行為不變