I'm using the PhotoView library to have a slide view of images. That's easy. Then I wanted set as wallpaper the image I wanted, maybe on click in a button but I have a problem! The library seems that not allows create a layout but only its in this way.
<com.ex.paper.HackyViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
So i can't add any button. I need detect the right array position and in some way set that image as wallpaper.. So far the code is this:
`public class MainActivity extends Activity
{
Bitmap bitmap;
int lastImageRef;
private static final String ISLOCKED_ARG = "isLocked";
private ViewPager mViewPager;
private static MenuItem menuLockItem;
private WallpaperManager wallpaper;
private static int[] sDrawables = { R.drawable.wallpapertwo, R.drawable.twixkatfirst, R.drawable.wallpaper,
R.drawable.sfondo, R.drawable.wallpapertre};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
setContentView(mViewPager);
mViewPager.setAdapter(new SamplePagerAdapter());
if (savedInstanceState != null) {
boolean isLocked = savedInstanceState.getBoolean(ISLOCKED_ARG, false);
((HackyViewPager) mViewPager).setLocked(isLocked);
}
}
static class SamplePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
WallpaperManager wallpaper = WallpaperManager.getInstance(container.getContext());
/*Toast number = Toast.makeText(container.getContext(), "wallpaper number "+position, Toast.LENGTH_LONG);
number.show();*/
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
try
{
wallpaper.setResource(sDrawables[position]);
}
catch (IOException e)
{
}
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}`
Now, in the try catch, I can set the wallpaper through position but without tapping any button!! And of course it's not a good way. Any solution? Maybe a button in the actionbar? But I can't find the array position at that point.
You can use FrameLayout:
<FrameLayout...>
<com.ex.paper.HackyViewPager/>
<Button/>
<FrameLayout/>
In onCreate:
setContentView(your.layout.with.frameLayout);
mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
wallpaper.setResource(sDrawables[mViewPager.getCurrentItem()]);
}
});
}
Related
I am relatively new to writing apps and I am currently working at my second project. I have an activity called AddNetwork, which contains a button that should open an AlertDialog. In the AlertDialog I want to have a TabLayout with two tabs, that each show different content. I have been trying to achieve this for about 8 hours and I have found a few tutorials that partially cover my problem, but nothing that is really on point. I think I could solve my problem using ViewPager2, but I haven't managed to get it working yet. As of now my code works as follows:
AddNetwork.java creates an instance of AlertDialogSelectWifi.java, which extends DialogFragment and inflates the alertdialog_select_wifi.XML layout file that contains a TabLayoutand a ViewPager2. Also in the DialogFragment, I am trying to set an adapter to the viewPager, namely ViewPagerAdapter.java, which extends FragmentStateAdapter. From there I would want to attach the two fragments AlertDialogRecentFragment.java (with fragment_alert_dialog_recent.xml) and AlertDialogTypeFragment.java (with fragment_alert_dialog_type.xml). Note that the latter is not yet included in the code, so as of now I would only add one fragment to the tabs (I guess).
So at the moment, my code is a somewhat chaotic mixture of all the tutorials I found and followed. It does not cause any errors and I am able to open the Alertdialog, however, the fragment_alert_dialog_recent.xml and the tabs are not visible.
I really don't know what else I could try or change in my code. Overall I am not sure whether it is correct to set the ViewPagerAdapter in the AlertDialogSelectWifi.java file or not. What am I missing or doing wrong? Any help is grealty appreciated!
Here is my code:
AddNetwork.java
public class AddNetwork extends AppCompatActivity {
Context context = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_network);
//BUTTON
final MaterialButton buttonSelectWifi;
buttonSelectWifi = (MaterialButton) findViewById(R.id.button2);
buttonSelectWifi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//CREATE ALERT DIALOG
FragmentManager fm = getSupportFragmentManager();
DialogFragment dialog = AlertDialogSelectWifi.newInstance(context);
dialog.show(fm, "dialog");
}
});
}
}
AlertDialogSelectWifi.java
public class AlertDialogSelectWifi extends DialogFragment {
static Context mContext;
public static AlertDialogSelectWifi newInstance(Context context) {
mContext = context;
return new AlertDialogSelectWifi();
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
LayoutInflater inflater = requireActivity().getLayoutInflater(); //getActivity().getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alertdialog_select_wifi, null);
builder.setTitle("Add Saved Network")
.setView(alertLayout)
.setCancelable(true)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.alertdialog_select_wifi, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager2 viewPager = view.findViewById(R.id.viewpager);
TabLayout tabLayout = view.findViewById(R.id.tablayout);
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity(), mContext, viewPager);
viewPager.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
}
ViewPageAdapter.java
public class ViewPagerAdapter extends FragmentStateAdapter {
private LayoutInflater mInflater;
private ViewPager2 viewPager;
public ViewPagerAdapter(FragmentActivity fragmentActivity, Context context, ViewPager2 viewPager) {
super(fragmentActivity);
this.mInflater = LayoutInflater.from(context);
this.viewPager = viewPager;
}
#NonNull
#Override
public Fragment createFragment(int position) {
return AlertDialogRecentFragment.newInstance();
}
#Override
public int getItemCount() {
return 0;
}
}
if i understood your problem correctly change your adapter like this:
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
if(position == 0)
return new AlertDialogRecentFragment();
else
return new AlertDialogTypeFragment();
}
#Override
public int getItemCount() {
return 2;
}
}
I've made a image slider with help of viewpager and picasso, now i want to add next, prev button on the image, how can i do that?
I saw different answers of this but all of them are showing error
This is main activity where image slider is shown:
public class MainActivity extends AppCompatActivity {
private int[] imageUrls = new int[]{
R.drawable.after_cookie,
R.drawable.before_cookie
};
private WebBackForwardList viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.view_pager);
ViewPageAdapter adapter = new ViewPageAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
}
}
This is ViewPageAdapter:
public class ViewPageAdapter extends PagerAdapter {
private Context context;
private int[] imageUrls;
ViewPageAdapter(Context context, int[] imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
Picasso.get()
.load(imageUrls[position])
.fit()
.centerCrop()
.into(imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
add this method to your code
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
then use this for next button
Button NextButton = (Button)findViewById(R.id.button1);
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(getItem(+1), true); //getItem(+1) for next
}
});
and use this for the previous button
Button PreviousButton = (Button)findViewById(R.id.button2);
PreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(getItem(-1), true); //getItem(-1) for previous
}
});
it will work fine ;)
I am showing random images in gridview using string array urls with picasso in first activity and when I'm clicking on any image in gridview then I want to show that exact random image in next activity. i am using put extra and sending that position like int r = random.nextInt(array.length); I'm using that r into gridview put extra as position. but when i m setting that r in imageview its showing another random image not exact.
This is my code
public class MainActivity extends Activity {
static Random random;
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
static int p;
// Some items to add to the GRID
static final String[] icons= {
"https://abhiandroid.com/ui/wp-content/uploads/2015/12/horizontalSpacing-in-Gridview.jpg",
"http://www.whatsappstatusmessages.com/wp-content/uploads/2017/01/whatsapp-dp-images-in-english.jpg",
"http://www.sarkarinaukrisearch.in/wp-content/uploads/2019/02/whatsapp-dp-status-in-english-1-77.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://4.bp.blogspot.com/-2iawNx83Kpw/XL21pPj0aPI/AAAAAAAAKiE/VRR7pupbWDUj0TNNAKdGH8Baaz_c9IcSgCLcBGAs/s1600/ss.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://3.bp.blogspot.com/-8us6YRiZEh0/XL21c6ibbXI/AAAAAAAAKh4/eNyjErq7q04YCeWxDPWojYfOoAC8BCodwCLcBGAs/s1600/s.jpg"
};
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.albumGrid);
CustomAdopter customAdopter=new CustomAdopter();
gridView.setAdapter(customAdopter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", p);
startActivity(intent);
}
});
}
private static class CustomAdopter extends BaseAdapter {
static int p;
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.phototem, null);
ImageView imageView = view.findViewById(R.id.cover);
random = new Random(); // or create a static random field...
p= random.nextInt(icons.length);
Picasso.get().load(icons[p]).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView);
return view;
}
}
Showing Image in this Activity
public class SwipeView extends Activity
{
int positions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
positions = i.getExtras().getInt("id");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(technoapps4.goodnightshayariworld.MainActivity.p);
}
private class ImagePagerAdapter extends PagerAdapter
{
String[] icons =MainActivity.icons ;
#Override
public int getCount()
{
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
Context context = SwipeView.this;
ImageView imageView = new ImageView(context);
Picasso.get().load(icons[position]).into(imageView);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((ImageView) object);
}
}
}
For this purpose, you should create an Interface and pass the random position though that interface.
And the variable p isn't the clicked item position. The value of p is changing continuously while the gridView is populating items.
Edit:
Create an Interface like this:
public interface ItemClickListener {
void onItemClick(int position);
}
Now initialize the ItemClickListener instance inside your CustomAdopter class using the public setter.
public void setItemClickListener(ItemClickListener clickListener) {
onItemClickListener = clickListener;
}
and finally, add the following code inside the getview method to pass your adapter position to the listener.
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(p);
}
});
Now instead of GridView's OnItemClickListener(), use this interface to get the correct position. like this-
gridView.setAdapter(customAdopter);
customAdopter.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int position) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", position);
startActivity(intent);
}
});
I was going to provide you an alternative to this issue which is to use a recyclerview with gridLayoutManager and create a Custom layout that implements RecyclerView.Adapter....All of this might seem confusing to you I guess, so I quickly create a Unit Test to simulate what your code wants to achieve and below is the result.
public class ExampleUnitTest {
private static String data = null;
#Test
public void setParentData(){
data = "I set You";
Subclass subclass = new Subclass();
subclass.getParentData();
}
private static class Subclass{
void getParentData(){
assertEquals("I set You", data);
}
}
}
//Tests passed
I will take a minute to explain this, since you have your custom adapter as a subclass of MainActivity, then I believe that the subclass should have access to some values of its parent class.
I am talking about this: static int p; so you don't need to create two of that like you created in the subclass also which is the CustomAdopter class.
So below is the modification to your code and I believe it should work as far as the test passed, else, pls let me know so I can take a look again.
This is not really an answer but it's the only way I can share code and explain some things in details.
public class MainActivity extends Activity {
static Random random;
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
static int p;
// Some items to add to the GRID
static final String[] icons= {
"https://abhiandroid.com/ui/wp-content/uploads/2015/12/horizontalSpacing-in-Gridview.jpg",
"http://www.whatsappstatusmessages.com/wp-content/uploads/2017/01/whatsapp-dp-images-in-english.jpg",
"http://www.sarkarinaukrisearch.in/wp-content/uploads/2019/02/whatsapp-dp-status-in-english-1-77.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://4.bp.blogspot.com/-2iawNx83Kpw/XL21pPj0aPI/AAAAAAAAKiE/VRR7pupbWDUj0TNNAKdGH8Baaz_c9IcSgCLcBGAs/s1600/ss.jpg",
"https://www.trueshayari.in/wp-content/uploads/2018/07/Love-Status-DP-for-Couple.jpg",
"https://3.bp.blogspot.com/-8us6YRiZEh0/XL21c6ibbXI/AAAAAAAAKh4/eNyjErq7q04YCeWxDPWojYfOoAC8BCodwCLcBGAs/s1600/s.jpg"
};
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.albumGrid);
random = new Random(); // or create a static random field...
p= random.nextInt(icons.length);
CustomAdopter customAdopter=new CustomAdopter();
gridView.setAdapter(customAdopter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SwipeView.class);
intent.putExtra("id", p);
startActivity(intent);
}
});
}
private static class CustomAdopter extends BaseAdapter {
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.phototem, null);
ImageView imageView = view.findViewById(R.id.cover);
Picasso.get().load(icons[p]).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView);
return view;
}
}
Here I have developed an app to view full screen images. I was able to develop it with swipe to move to next image. I have used a viewpager element.
How can I use onclick action to viewpager to do something.(delete, share etc..)
My code looks like below,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
Thread child=new Thread(){
#Override
public void run() {
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,utils.getFilePaths());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);//show the selected
btnMail=(Button)findViewById(R.id.btnMailThis);
btnRate=(Button)findViewById(R.id.btnRate);
btnMail.setVisibility(View.INVISIBLE);
btnRate.setVisibility(View.INVISIBLE);
}
};
child.start();
}
The FullScreenImageAdapter.java looks like below
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
//Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_full_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
//btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
/*
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});*/
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
Thanks in advance..!
You can create your own class inheriting ViewPager and override onInterceptTouchEvent like this:
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getAction() == MotionEvent.ACTION_UP) {
//Your code here
return false;
} else {
//Do this to keep swipes working. It will also make vertical swiping work. You can avoid the latter by handling MotionEvent action and x,y directions.
return super.onInterceptTouchEvent(arg0);
}
}
Don't forget to replace the ViewPager object in your xml with com.example.yourpackagename.YourViewPagerClass
I have an activity with some images and I'm using swipe to load the next image. I need when I touch the image to show a button, for image saving. How can I do that? Here's my code:
public class Photo_gallery extends Activity{
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
.
.
.
R.drawable.p108
};
public int getCount() {
return mImages.length;
}
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
public Object instantiateItem(ViewGroup container, int position) {
Context context = Photo_gallery.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
EDIT:
My XML code:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
If you just want it to show a button on the screen when you click the image, you can put a button in your layout with the parameter android:visibility="gone".
Then, when the user clicks the image (just put an OnClickListener() for the ImageView), call button.setVisibility(View.VISIBLE); to show the button. Then when the user performs any other action and you want to hide the button again, call button.setVisibility(View.GONE);