activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
<Button
android:id="@+id/buttonNext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:text="@string/nxt" />
</LinearLayout>
MainActivity.java
package com.mahi.imageswitcher;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class MainActivity extends Activity {
private ImageSwitcher imageSwitcher;
Button btnNext;
int imageIds[]={R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5,R.drawable.image6,};
int messageCount=imageIds.length;
int currentIndex=-1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById (R.id.buttonNext);
imageSwitcher = (ImageSwitcher) findViewById (R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewFactory()
{
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
return imageView;
}
});
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Output:


No comments:
Post a Comment