I am trying to follow a few different tutorials to have a ViewPager
that lets a user swipe through images and then set the currently viewed image as their wallpaper. so far I have not been successful in getting the wallpaper set, and there is an issue with performance as the user swipes through the photos, performance degrades dramatically.
public class MainActivity extends AppCompatActivity {
ViewPager mViewPager;
int[] mImages = {R.drawable.example__1_, R.drawable.example__2_, R.drawable.example__3_,
R.drawable.example__4_, R.drawable.example__5_, R.drawable.example__6_,
R.drawable.example__7_, R.drawable.example__8_, R.drawable.example__9_,
R.drawable.example__10_, R.drawable.example__11_, R.drawable.example__12_};
item mViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewPagerMain);
mViewPagerAdapter = new item(MainActivity.this, mImages);
mViewPager.setAdapter(mViewPagerAdapter);
final int set = mViewPager.getCurrentItem();
Button button = findViewById(R.id.SetWall);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Setting Wallpaper... 1/2", Toast.LENGTH_SHORT).show();
WallpaperManager wpm
= WallpaperManager.getInstance(getApplicationContext());
try {
Toast.makeText(MainActivity.this,
"Setting Wallpaper... 2/2", Toast.LENGTH_SHORT).show();
wpm.setResource(set);
Toast.makeText(MainActivity.this,
"Wallpaper Set!", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Toast.makeText(MainActivity.this,
"Error", Toast.LENGTH_SHORT).show();
}
}
});
}
Have you set the permission in your Manifest.xml file like this?
<uses-permission android:name="android.permission.SET_WALLPAPER" />
This is because your pages get destroyed and recreated every time they get off screen which happens when you swipe to the next.
To make ViewPager smoother use mViewPager.setOffscreenPageLimit(NumberOfPages-1);
after you set the adapter (mViewPager.setAdapter();
)