Search code examples
imageswitcher

It comes to Log1 then crashes.Whats wrong?


"is" is the ID of Imageswitcher

s is images number in array

The Array contains 5 images:play stop next previous pause

public class MainActivity extends AppCompatActivity {

Button btnnext,btnprev;
ImageSwitcher is;
int s;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   final Integer[] img=new Integer[]{R.drawable.next,R.drawable.play,R.drawable.previous,R.drawable.stop,R.drawable.pause,};
    btnnext=(Button)findViewById(R.id.btnnext);
    btnprev=(Button)findViewById(R.id.btnprev);
    is     =(ImageSwitcher) findViewById(R.id.is);
    Log.i("log1","1");

    is.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            ImageView imageView=new ImageView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

Whats wrong with the line below?

            imageView.setLayoutParams(new ImageSwitcher.LayoutParams
                    (LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
          is.setImageResource(img[s]);

Log.i("log","4"); return imageView;

        }
    });

Log.i("log2", "2");

Button Next codes:

        btnnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Animation right= AnimationUtils.loadAnimation(MainActivity.this,android.R.anim.slide_out_right);
            Animation left= AnimationUtils.loadAnimation(MainActivity.this,android.R.anim.slide_in_left);
            is.setAnimation(left);
            is.setAnimation(right);
            is.setImageResource(img[(s+1)]);
        }
    });

Log.i("log3", "3");

Button Previous codes:

        btnprev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Animation right= AnimationUtils.loadAnimation(MainActivity.this,android.R.anim.slide_out_right);
            Animation left= AnimationUtils.loadAnimation(MainActivity.this,android.R.anim.slide_in_left);
            is.setAnimation(left);
            is.setAnimation(right);
            is.setImageResource(img[(s-1)]);
}
});
}
}

Solution

  • this code should be removed:

       is.setImageResource(img[s]);
    

    instead of:

       is.setImageResource(img[(s+1)]);
    

    I shoul use:

       currentImage++;
                currentImage = currentImage % img.length;
                is.setImageResource(img[currentImage]);
    

    and instead of:

        is.setImageResource(img[(s-1)]);
    

    I should use:

        currentImage--;
                 currentImage = (currentImage + img.length) % img.length;
                is.setImageResource(img[currentImage]);