I'm Beginner. I want change my image on imageview in Android and that images are periodically changed after some interval.
<LinearLayout
android:id="@+id/la_01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eb68a3"
android:orientation="vertical" >
<ImageView
android:id="@+id/ig1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center"
android:src="@drawable/a03" />
</LinearLayout>
public class MainActivity2 extends Activity {
private ImageView ig1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
int[] imageArray = new int[] {
R.drawable.a01, R.drawable.a02, R.drawable.a04, R.drawable.a05, R.drawable.a06
};
ig1.setImageResource(R.drawable.a06);
How can I do ?
please help me ,thanks
You can use Handler
class to do this.
public class ImageSwitcherActivity extends Activity implements Runnable{
private Handler mHandler = new Handler();
ImageView imageView;
static int idx = 0;
int[] images;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_switcher);
images = new int[]{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7
};
imageView = (ImageView) findViewById(R.id.ig1);
mHandler.removeCallbacks(this);
mHandler.postDelayed(this, 100);
}
@Override
public void run() {
idx = new Random().nextInt(images.length - 1);
imageView.setImageResource(images[idx]);
mHandler.postDelayed(this, ( 2 * 1000)) ;
}
@Override
public void onStop()
{
super.onStop();
mHandler.removeCallbacks(this);
}
}
Create a random function which return the position you can use to switch images...
public class MainActivity extends Activity {
int[] img = {
R.drawable.image1,
R.drawable.app_background,
R.drawable.app_background_p,
R.drawable.list
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView)this.findViewById(R.id.image);
int get = GetRemdom(0,3); // 0 to (length of your array -1)
image.setBackgroundResource(img[get]);
}
public int GetRemdom(int min,int max){
Random random = new Random();
int position = random.nextInt(max - min + 1) + min;
return position ;
}