2013-03-30 36 views
-3

我只是想將多個圖像添加到android活動。我將不得不通過使用下一個和上一個按鈕來瀏覽那些圖像。只需幫助我,我們如何存儲多個圖像,以及如何瀏覽它們? 謝謝。在android中的圖像導航

+0

搜索關於相冊和/或ViewPager – Shehabix

回答

1

最簡單的解決方案之一是在數組中存儲可繪製的ID並在ImageView中顯示其中的一個。看這個。

public class MainActivity extends Activity implements View.OnClickListener { 

    private static final int PREV_BUTTON_ID = 0; 
    private static final int NEXT_BUTTON_ID = 1; 

    private ImageView mImage; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mImage = (ImageView) findViewById(R.id.image); 
     mImage.setImageResource(getFirstImageId()); 

     Button prevButton = (Button) findViewById(R.id.btnPrev); 
     prevButton.setId(PREV_BUTTON_ID); 
     prevButton.setOnClickListener(this); 

     Button nextButton = (Button) findViewById(R.id.btnNext); 
     nextButton.setId(NEXT_BUTTON_ID); 
     nextButton.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View view) { 
     switch (view.getId()) { 
      case PREV_BUTTON_ID: 
       mImage.setImageResource(getPrevImageId()); 
       break; 
      case NEXT_BUTTON_ID: 
       mImage.setImageResource(getNextImageId()); 
       break; 
      default: 
       break; 
     } 
    } 

    private static final int[] sImages = { R.drawable.image1, R.drawable.image2, R.drawable.image3 }; 

    private int mCurrentImageId; 

    private int getFirstImageId() { 
     return sImages[mCurrentImageId]; 
    } 

    private int getNextImageId() { 
     mCurrentImageId++; 

     if (mCurrentImageId > sImages.length - 1) { 
      mCurrentImageId = sImages.length - 1; 
     } 

     return sImages[mCurrentImageId]; 
    } 

    private int getPrevImageId() { 
     mCurrentImageId--; 

     if (mCurrentImageId < 0) { 
      mCurrentImageId = 0; 
     } 

     return sImages[mCurrentImageId]; 
    } 
} 

和佈局是

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="horizontal" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent"> 
    <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Prev" 
      android:id="@+id/btnPrev" 
      android:layout_gravity="center_vertical"/> 
    <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/image" 
      android:layout_gravity="center" 
      android:layout_weight="1" 
      android:scaleType="center" 
      android:focusableInTouchMode="false"/> 
    <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Next" 
      android:id="@+id/btnNext" 
      android:layout_gravity="center"/> 
</LinearLayout> 
+0

嘿謝謝它對我非常有用 – Reena