How to use ImageSwitcher in Android App
Please follow the steps below in order to use ImageSwitcher in Android Application:
1.Click on ImageSwitcher. Drag it in the center of the screen as shown. This option allows you to switch between images.
2.Go to text. Add an id for the ImageSwitcher.
3.Go to MainActivity.java. Show the ImageView and set the scale type.
4.Show the button in MainActivity.java as private button pr, nx
5.Add OnClickListener for the button.
6.Copy the highlighted portion in blue. Paste it just below and replace ‘pr’ with ‘nx’.
7.Go to live view screen. Press Next button and you can see black Android logo. Press the Previous button and you can see a green Android logo.
Complete Code For Image Swither in Android
app-java-MainActivity.java
package com.sabithpkcmnr.alertdialogexit;
import ...
public class MainActivity extends AppCompatActivity {
private ImageSwitcher sw;
private Button px,nx;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sw = (ImageSwitcher) findViewById(R.id.imgsw);
pr = (Button) findViewById(R.id.pr);
nx = (Button) findViewById(R.id.nx);
sw.setFactory(new ViewSwitcher.ViewFactory () {
@Override
public View makeView() {
ImageView imageView = new ImageView (getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
});
pr.setOnClickListener(new View.OnClickListener() {
@Override
public void onCLick(View v) {
sw.setImageResource(R.drawable.thd)
}
});
nx.setOnClickListener(new View.OnClickListener() {
@Override
public void onCLick(View v) {
sw.setImageResource(R.drawable.thu)
}
});
}
}
app-res-layout-activity_main.xml
<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout xmlns="http://schema.android.com/apk/res/android"
xmlns:tools="http://schema.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="com.sabithpkcmnr.alertdialogexit.MainActivity">
<ImageSwitcher
android:id="@+id/imgsw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal=="true" />
<Button
android:id="Previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/pr" />
<Button
android:id="Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/nx" />
</RelativeLayout>