ImageSwitcher fornisce un commutatore per passare da un’immagine all’altra. Per utilizzare ImageSwitcher, dobbiamo implementare il suo componente nel file .xml:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android“
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<ImageSwitcher
android:id=”@+id/imageswitcher”
android:layout_width=”match_parent”
android:layout_height=”250dp”/>
<Button
android:id=”@+id/next”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Next”
android:textColor=”#FFBBFF”/>
<Button
android:id=”@+id/previous”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Previous”
android:textColor=”#FFAAFF”/>
</LinearLayout>
Con Il metodo setFactory() implementiamo l’interfaccia ViewFactory per restituire ImageView:
package com.example.imageSwitcher.activities;
import android.app.Activity;
import android.os.Bundle;
import com.example.imageSwitcher.R;
import android.widget.*;
import android.view.*;
public class MainActivity extends Activity {
ImageSwitcher imageSwitcher;
Button btn1,btn2;
int images[] = {R.mipmap.ic_launcher,R.mipmap.ic_launcher1};
int count = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.next);
imageSwitcher =findViewById(R.id.imageswitcher);
btn2= findViewById(R.id.previous);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
ImageView imageView = new ImageView( getApplicationContext() );
return imageView;
}
});
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(count<images.length-1){
count=count+1;
imageSwitcher.setImageResource(images[count]);
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count>0){
count=count-1;
imageSwitcher.setImageResource(images[count]);
}
}
});
}
}