我試圖顯示一些圖像以及相關文本,但似乎無法弄清楚如何通過ImageButton onclick事件正確循環它們。我想要做的就是每次單擊按鈕時轉到下一張圖片。一旦我達到目的,就重新開始。如何通過單擊循環訪問LinkedHashMap中的數據
這裏是我的代碼。它可能不是最優雅的,但似乎工作,除了「currentid」以某種方式改變,所以我從來沒有在foreach循環中找到當前圖像。
public class Fundamentals extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fundamentals);
//Ojbects for forward and back buttons
ImageButton forwardButton = (ImageButton) findViewById(R.id.forward_button);
//image object
ImageView imageview = (ImageView) findViewById(R.id.fundamentals_image);
//Object for picture text
TextView textview = (TextView) findViewById(R.id.fundamentals_text);
//Images and associated text
Map<Integer, String> fundamentalPics = new LinkedHashMap<Integer, String>();
fundamentalPics.put(R.drawable.fund1, "some interesting text");
fundamentalPics.put(R.drawable.fund2, "more interesting text");
fundamentalPics.put(R.drawable.fund3, "and more");
//Set initial image
Map.Entry<Integer,String> pic = (Map.Entry<Integer, String>) fundamentalPics.entrySet().iterator().next();
imageview.setImageResource(pic.getKey());
textview.setText(pic.getValue());
imageview.setTag(fundamentalPics);
}
public void setImage(View v) {
//Object for picture text
TextView textview = (TextView) findViewById(R.id.fundamentals_text);
//Object for picture image
ImageView imageview = (ImageView) findViewById(R.id.fundamentals_image);
//get current id
Integer currentid = imageview.getId();
Map<Integer, String> fundamentalPics = (LinkedHashMap<Integer, String>) imageview.getTag();
Boolean foundImage = false;
for (Map.Entry<Integer, String> pic : fundamentalPics.entrySet())
{
if (foundImage.equals(true)) {
textview.setText(pic.getValue());
imageview.setImageResource(pic.getKey());
break;
}
//cycle until we find current image
if (pic.getKey().equals(currentid)) {
foundImage = true;
if (!fundamentalPics.entrySet().iterator().hasNext()) {
//we've reached the end. go to beginning....
Map.Entry<Integer,String> item = (Map.Entry<Integer, String>) fundamentalPics.entrySet().toArray()[0];
textview.setText(item.getValue());
imageview.setImageResource(item.getKey());
}
}
}
}
爲什麼你不保留那個pic對象在實例級別,所以你可以訪問任何回調方法,而不是從image.getTag獲取它。而且你可以保持當前圖像索引的實例級別,它將簡化邏輯。只是一個建議。 – sampathpremarathna