2016-09-30 3 views
1

Je suis en mesure de définir une image individuelle de la drawable comme fond d'écran d'accueil Android/fond d'écran via le code comme indiqué ci-dessousComment définir un diaporama d'images comme écran d'accueil Android (fond d'écran) par programme?

WallpaperManager myWallpaperManager 
         = WallpaperManager.getInstance(getApplicationContext()); 
       try { 
        myWallpaperManager.setResource(+ R.drawable.splash); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

Ce que je veux savoir est comment afficher un diaporama d'images. Plus comme l'image est modifiée après un intervalle de temps particulier, disons 2 minutes. Considérant le fait que c'est possible et déjà implémenté dans plusieurs applications basées sur des fonds d'écran disponibles sur Google Play Store, veuillez partager avec moi un exemple de code ou des liens.

Je n'ai pas l'intention de garder l'application ouverte ou en arrière-plan en tout temps. J'ai fait beaucoup de recherches en ligne mais je ne suis pas capable de trouver des exemples ou des méthodes efficaces pour le faire. S'il y a un défaut de performance à l'idée, je suis ouvert aux suggestions.

++ Je vous prie de me préciser afin d'éviter toute confusion. Je suis capable de définir une image particulière comme fond d'écran de mon appareil (pas de mise en page ou d'écran dans mon application). Mon exigence est de changer cette image particulière de temps en temps compte tenu du fait, Disons que j'ai une douzaine d'images.

Merci à l'avance

Répondre

1

Vous devez d'abord importer cette bibliothèque impressionnante https://github.com/JakeWharton/ViewPagerIndicator

Les prochaines étapes sont très simples je vous donne mon propre code de travail

il vous suffit de copier coller et remplacer selon toi.

Première copie cette classe POJO

public class Banner { 

    private String str_id; 
    private String str_photo; 

    Banner() { 

    } 

    public Banner(String str_id, String str_photo) { 
     this.str_id = str_id; 
     this.str_photo = str_photo; 
    } 

    public String getStr_id() { 
     return str_id; 
    } 

    public void setStr_id(String str_id) { 
     this.str_id = str_id; 
    } 

    public String getStr_photo() { 
     return str_photo; 
    } 

    public void setStr_photo(String str_photo) { 
     this.str_photo = str_photo; 
    } 


} 

maintenant cet adaptateur:

public class SlidingImage_Adapter extends PagerAdapter { 

    private List<Banner> IMAGES = new ArrayList<Banner>(); 
    private LayoutInflater inflater; 
    private Context context; 
    private Typeface typefaceReguler, typefaceLight, typefaceItalic; 

    public SlidingImage_Adapter(Context context, List<Banner> IMAGES) { 
     this.context = context; 
     this.IMAGES = IMAGES; 
     inflater = LayoutInflater.from(context); 
     System.out.println("----imagesssss----- "+IMAGES); 
     /* typefaceReguler = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular_0.ttf"); 
     typefaceLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light_0.ttf"); 
     typefaceItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic_0.ttf");*/ 
    } 

    @Override 
    public void destroyItem(ViewGroup container, int position, Object object) { 
     container.removeView((View) object); 
    } 

    @Override 
    public int getCount() { 
     return IMAGES.size(); 
    } 

    @Override 
    public Object instantiateItem(ViewGroup view, int position) { 
     View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false); 

     Banner banner = IMAGES.get(position); 
     assert imageLayout != null; 
     final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image); 
     final ImageView img_browse = (ImageView) imageLayout.findViewById(R.id.imageView_Browse); 
     final TextView textView = (TextView) imageLayout.findViewById(R.id.textView_collectiontitle); 
//  textView.setTypeface(typefaceReguler); 
//  textView.setTextSize(AppController.textSize(context, 30)); 
//  textView.setTextColor(ContextCompat.getColor(context, R.color.white)); 
//  int width = imageView.getLayoutParams().width = AppController.screenWidth(context)/1; 
//  int height = imageView.getLayoutParams().height = AppController.screenHeight(context)/3; 

     img_browse.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Toast.makeText(context, "Browse Collection", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     if (position == 0) { 
      textView.setText("woodland original"); 


     } 
     if (position == 1) { 
      textView.setText("nike original"); 
     } 
     if (position == 2) { 
      textView.setText("rebook original"); 
     } 
     if (position == 3) { 
      textView.setText("adidas original"); 
     } 
     if (!banner.getStr_photo().isEmpty()) 
     { 
      System.out.println("---Working---- "+banner.getStr_photo()); 
      Picasso.with(context) 
        .load("Your image here") 
        .placeholder(R.drawable.banner_shoe) // optional 
        .error(R.drawable.banner_shoe)  // optional 
        .resize(250, 200)      // optional 
        .rotate(90)        // optional 
        .into(imageView); 
     } 
     view.addView(imageLayout, 0); 
     return imageLayout; 
    } 

    @Override 
    public boolean isViewFromObject(View view, Object object) { 
     return view.equals(object); 
    } 

    @Override 
    public void restoreState(Parcelable state, ClassLoader loader) { 
    } 

    @Override 
    public Parcelable saveState() { 
     return null; 
    } 
} 

Maintenant, c'est l'activité principale

public class SlideAutomaticWithViewPager extends AppCompatActivity { 
    public List<Banner> list_banner = new ArrayList<Banner>(); 
    private SlidingImage_Adapter slidingImage_adapter; 
    private static ViewPager mPager; 
    private static int NUM_PAGES = 0; 
    private static int currentPage = 0; 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.slide_automatic); 

     list_banner.add(new Banner("1", "Your image link here")); 
     list_banner.add(new Banner("2", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png")); 
     list_banner.add(new Banner("3", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png")); 
     list_banner.add(new Banner("4", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png")); 

     mPager = (ViewPager) findViewById(R.id.viewpagerHome); 
     slidingImage_adapter = new SlidingImage_Adapter(this, list_banner); 
     mPager.setAdapter(slidingImage_adapter); 

     CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator); 

     indicator.setViewPager(mPager); 

     final float density = getResources().getDisplayMetrics().density; 

     indicator.setRadius(5 * density); 

     NUM_PAGES = list_banner.size(); 


     // Auto start of viewpager 
     final Handler handler = new Handler(); 
     final Runnable Update = new Runnable() { 
      public void run() { 
       if (currentPage == NUM_PAGES) { 
        currentPage = 0; 
       } 
       mPager.setCurrentItem(currentPage++, true); 
      } 
     }; 
     Timer swipeTimer = new Timer(); 
     swipeTimer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       handler.post(Update); 
      } 
     }, 3000, 3000); 

     // Pager listener over indicator 
     indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 

      @Override 
      public void onPageSelected(int position) { 
       currentPage = position; 

      } 

      @Override 
      public void onPageScrolled(int pos, float arg1, int arg2) { 

      } 

      @Override 
      public void onPageScrollStateChanged(int pos) { 

      } 
     }); 


    } 
} 

Vous pouvez essayer ce code.

+0

Salut danois, je vous remercie de votre volonté d'aider. Mais ma question si regardé clairement indique que mon exigence est de définir un diaporama d'images comme fond d'écran de mon appareil (écran d'accueil android). Pas mon écran d'application mais l'écran de mon appareil. Aide aimablement. Merci d'avance. –

+0

souhaite que quelqu'un sache que j'ai tâche et ne peut trouver un seul exemple ou tutoriel pour le papier peint change les images :( – CJS

0

salut Shyamnath Mallinathan,

Mettez toutes les images dans le viewpager et désactiver la fonctionnalité de viewpager swipe.

Mettre en oeuvre une minuterie pour faire glisser les pages viewpager après toutes les 2 secondes

!! Bonne programmation

+0

Salut mohit, J'ai demandé à propos de la configuration de l'image à l'écran de mon appareil (écran d'accueil android) pas une disposition dans l'écran de l'application. –

0

Mettez vos images dans un viewpager puis dans l'adaptateur de votre son activité onCreate charger le téléavertisseur de vue, puis:

Runnable runnable = new Runnable() { 
       @Override 
       public void run() { 
        for (int i = 0; i < mAdapter.getCount()-1; i++) { 
         final int value = i; 
         try { 
          Thread.sleep(50); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
         handler.post(new Runnable() { 
          @Override 
          public void run() { 
           mPager.setCurrentItem(value, true); 
          } 
         }); 
        } 
       } 
      }; 
      new Thread(runnable).start(); 

     } 
+0

Salut n9153, je suppose que vous n'êtes toujours pas clair sur ma question Mes excuses Mon exigence est de définir l'image à l'écran d'accueil de l'appareil, pas dans l'application. Cela devrait changer de temps en temps. –

0

Je suis mort pendant des semaines pour faire une séquence d'images live wallpaper finalement trouvé une façon et vous pouvez le contrôle avec le temps entre les images et il est un service si u ne pas besoin d'ouvrir votre application seulement de paramètres - affichage --- live wallpaper - séquence d'images et fait

public class MainActivity extends WallpaperService { 

@Override 
public Engine onCreateEngine() { 
    return new WallpaperEngine(); 
} 

class WallpaperEngine extends Engine { 
    //Duration between slides in milliseconds 
    private final int SLIDE_DURATION = 2000; 

    private int[] mImagesArray; 
    private int mImagesArrayIndex = 0; 
    private Thread mDrawWallpaper; 
    // private String mImageScale = "Fit to screen"; 
    private CustomWallpaperHelper customWallpaperHelper; 

    public WallpaperEngine() { 
     customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources()); 
     mImagesArray = new int[] {R.drawable.garden1,R.drawable.garden2,R.drawable.garden3,R.drawable.garden4,R.drawable.girl1, 
       R.drawable.girl2,R.drawable.greenww,R.drawable.sports1,R.drawable.sports2,R.drawable.sports3,R.drawable.sports4}; 

     mDrawWallpaper = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        while (true) { 
         drawFrame(); 
         incrementCounter(); 
         Thread.sleep(SLIDE_DURATION); 
        } 
       } catch (Exception e) { 
        // 
       } 
      } 
     }); 

     mDrawWallpaper.start(); 
    } 

    private void incrementCounter() { 
     mImagesArrayIndex++; 

     if (mImagesArrayIndex >= mImagesArray.length) { 
      mImagesArrayIndex = 0; 
     } 
    } 

    private void drawFrame() { 
     final SurfaceHolder holder = getSurfaceHolder(); 

     Canvas canvas = null; 

     try { 
      canvas = holder.lockCanvas(); 

      if (canvas != null) { 
       drawImage(canvas); 
      } 
     } finally { 
      if (canvas != null) { 
       holder.unlockCanvasAndPost(canvas); 
      } 
     } 
    } 

    private void drawImage(Canvas canvas) 
    { 

     Bitmap image = BitmapFactory.decodeResource(getResources(), 
       mImagesArray[mImagesArrayIndex]); 
     Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true); 
     canvas.drawBitmap(b, 0,0, null); 
    } 

CustomWallpaperHelper

public class CustomWallpaperHelper { 
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to screen"; 

public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen"; 

private Context mContext; 
private Resources mResources; 

private Point screenSize = new Point(); 

private Bitmap bgImageScaled; 
private Point bgImagePos = new Point(0, 0); 

public CustomWallpaperHelper(Context mContext, Resources mResources) { 
    this.mContext = mContext; 
    this.mResources = mResources; 

    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); 
    Display display = wm.getDefaultDisplay(); 

    screenSize.x = display.getWidth(); 
    screenSize.y = display.getHeight(); 

    ; 
} 

private void scaleBackground() { 
    String imageScale = "Stretch to screen"; 
    Bitmap bgImage = null; 

    if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) { 
     bgImagePos = new Point(0, 0); 
     bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true); 
    } 
} 

public void setBackground(Canvas canvas) { 
    if (bgImageScaled != null) { 
     canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null); 
    } else { 
     canvas.drawColor(0xff000000); 
    } 
} 

public int getScreenWidth() { 
    return screenSize.x; 
} 

public int getScreenHeight() { 
    return screenSize.y; 
} 

public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) { 
    Point imagePos = new Point(); 

    imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x))/2; 
    imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y))/2; 

    return imagePos; 
} 

public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) { 
    PointF canvasScale = new PointF(1f, 1f); 

    if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) { 
     canvasScale.x = getScreenWidth()/(1f * imageWidth); 
     canvasScale.y = getScreenHeight()/(1f * imageHeight); 
    } else { 
     boolean tooWide = false; 
     boolean tooTall = false; 

     if (getScreenWidth() < imageWidth) { 
      tooWide = true; 
     } 

     if (getScreenHeight() < imageHeight) { 
      tooTall = true; 
     } 

     if (tooWide && tooTall) { 
      int x = imageWidth/getScreenWidth(); 
      int y = imageHeight/getScreenHeight(); 

      if (x > y) { 
       canvasScale.x = getScreenWidth()/(1f * imageWidth); 
       canvasScale.y = 1; 
      } else { 
       canvasScale.x = 1; 
       canvasScale.y = getScreenHeight()/(1f * imageHeight); 
      } 
     } else if (tooWide) { 
      canvasScale.x = getScreenWidth()/(1f * imageWidth); 
      canvasScale.y = 1; 
     } else if (tooTall) { 
      canvasScale.x = 1; 
      canvasScale.y = getScreenHeight()/(1f * imageHeight); 
     } 
    } 

    return canvasScale; 
} 

bien sûr, ne pas oublier les perimissions manifeste