Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic set image path

Tags:

android

In my project, there are a number of images having back and forward images and all images having a common layout. On clicking back and next buttons new images should be displayed.

private int imageCounter = 0;
private ImageView imageView;
private int[] imageArray = {R.drawable.image_w_lbl_0, R.drawable.image_w_lbl_1,};
private int index_count = 0;
@Override
public void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.frame0);//this one is the common parent layout for all imageviews
    super.onCreate(savedInstanceState);
    imageView = new ImageView(this);

    ImageButton next = (ImageButton) findViewById(R.id.next);
    ImageButton back = (ImageButton) findViewById(R.id.back);
    next.setOnClickListener(this);
    back.setOnClickListener(this);

    //show the default image
    this.loadImage(imageArray[0]);

}
@Override
public void onClick(View v) 
{
    int imagePath = 0;
    // TODO Auto-generated method stub
    switch (v.getId())
    {
    case R.id.next:
        if(imageCounter < 25)
        {   
            imagePath = imageArray[index_count];
        }
        imageCounter++;
        break;
    case R.id.back:
        if(imageCounter > 0)
        {
            //imagePath =
        }
        imageCounter--;

        break;      
    }
    this.loadImage(imagePath);
}

private void loadImage(int imagePath)
{
    imageView.setImageResource(imagePath);
}

I am able to see my layout only in the output having back and forward buttons with the black background not an image from my drawable folder.

XML Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">

    <ImageButton android:id="@+id/back" android:src="@drawable/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"/>

    <ImageButton 
        android:id="@+id/next"
        android:src="@drawable/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right" />

</LinearLayout>
like image 533
maddy Avatar asked Dec 18 '25 01:12

maddy


1 Answers

int array of images from resources (i.e. res/drawable-mdpi):

Integer[] imageArray = { "R.drawable.img1", "R.drawable.img2" }

...

imageView.setImageResource(imageArray[0]); // displays img1

like image 187
yosh Avatar answered Dec 19 '25 15:12

yosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!