I'm trying to make a drag and drop from a custom slider.
The slider is in a viewPager and is shows Imageviews.
I don't know witch ID I should set to my longClickListener.
I tried the Imagview (swip_image_view) but it return null.
& it doesn't work with the viewpager.
Why is my longClickListener not working?
public class Activity_Kind extends Activity {
ViewPager viewPager;
CustomHorizontalSwip customHorizontalSwip;
private GridView gridDieren;
private ImageView bus;
private ImageView slider;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kies_dier);
gridDieren = (GridView) findViewById(R.id.gridSelectDieren);
text = (TextView) findViewById(R.id.kiesdiertext);
bus = (ImageView) findViewById(R.id.imageBus);
viewPager = (ViewPager) findViewById(R.id.viewPager);
customHorizontalSwip = new CustomHorizontalSwip(this);
viewPager.setAdapter(customHorizontalSwip);
viewPager.setLongClickable(true);
viewPager.setOnLongClickListener(longClickListener);
//slider = (ImageView) findViewById(R.id.swip_image_view);
//slider.setOnLongClickListener(longClickListener);
bus.setOnDragListener(dragListener);
}
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder myShadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, myShadowBuilder, v, 0);
return true;
}
};
View.OnDragListener dragListener = new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
int dragEvent = event.getAction();
switch (dragEvent) {
case DragEvent.ACTION_DRAG_ENTERED:
final View view = (View) event.getLocalState(); //Krijgt alle informatie van die view die wordt gedraged
if (view.getId() == R.id.imageBus);
text.setText("Werkt");
//gridDieren.addView(view);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
case DragEvent.ACTION_DROP:
break;
}
return true;
}
};
}
public class CustomHorizontalSwip extends PagerAdapter {
private int [] imageResources ={R.drawable.beer,R.drawable.bever, R.drawable.kip, R.drawable.leeuw, R.drawable.nijlpaard, R.drawable.poes
,R.drawable.ezel,R.drawable.hond, R.drawable.ooievaar, R.drawable.varken, R.drawable.wormpje};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomHorizontalSwip(Context c) {
ctx=c;
}
#Override
public int getCount() {
return imageResources.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
}
Your image swip_image_view is inside layout custom_swipe_dieren.xml. You should set onLongClickListener inside CustomHorizontalSwip -> instantiateItem() method like this :
public class CustomHorizontalSwip extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
imageView.setOnLongClickListener(longClickListener);
container.addView(itemView);
return itemView;
}
/* Declare and Initialise longClickListener in this file also */
/* Also do same for dragListener in this file */
}
This will work for you
Thanks
Related
I have a gridView on my mainScreen fragment which contains imageViews initialized by my ImageAdapter.java class. I also have another fragment which also has a gridView which follows the same initialization process. What i want is to pass the selected imaveView's icon(which is stored in an Integer[] array) to the other fragment's gridView.
Here are my classes:
MainFragment.java [the part that handles the image passing]:
// When an item in the context menu gets selected, call a method
#Override
public boolean onContextItemSelected(MenuItem item) {
// Get some extra info about the contextMenu
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position; // clicked view's position
if(item.getTitle().equals("Add Card to GLB")) {
addCardMessage(position, "added to GLB");
addSelectedCardToGlobalUserBox(position);
} else if (item.getTitle().equals("Add Card to JP")) {
addCardMessage(position , "added to JP");
} else
{
return false;
}
return false;
}
/**
* Creates a snackbar message, telling the user which card was added to which box
* #param id The position of the chosen card
* #param text Defines into which User Box the card was added
*/
private void addCardMessage(int id, String text) {
final Snackbar snackbar = Snackbar.make(gridView, id + " " + text ,Snackbar.LENGTH_LONG);
snackbar.setAction("Dismiss", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
snackbar.setActionTextColor(Color.MAGENTA);
snackbar.show();
}
private void addSelectedCardToGlobalUserBox(int position) {
ImageAdapter imageAdapter = new ImageAdapter(getContext());
UserBoxGlbImageAdapter userBoxGlbImageAdapter = new UserBoxGlbImageAdapter(getContext());
userBoxGlbImageAdapter.getGLBIconsList().add(imageAdapter.getmThumbIds(position));
int glbiconSize = userBoxGlbImageAdapter.getCount();
Toast.makeText(getActivity(), "Selected icon: " + imageAdapter.getmThumbIds(position), Toast.LENGTH_SHORT).show();
}
ImageAdapter.java [above fragment's adapter]:
public class ImageAdapter extends BaseAdapter {
Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer getmThumbIds(int index) {
return mThumbIds[index];
}
// References to our images
private Integer[] mThumbIds = {
R.mipmap.turvegitossj_phy,
R.mipmap.goget_ur_int,
R.mipmap.turgogetassj4_teq,
R.mipmap.turgotenksssj_uragl,
R.mipmap.lr_phy_trunks_ssj
};
}
SecondFragment.java:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
SecondFragmentAdapter[the one to receive the image]:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
}
So far, when i long-press and the context menu opens, i click on add card to GLB but the image doesn't pass to the 2nd fragmnet's gridView. From what i understand, the Integer that i am using to add the imageResource to the 2nd grid does not work properly. What do i need to do? Do i need to use a different var type for my receiver list?
Used ViewPager for images sliding, when clicking on each image must do an action, its different action from image to another,
I'm new to android development
so I try to add onClick listener to ViewPager, but I can't achieve it,
please any suggestion how to implement OnClickListener so when I click the first image will do action and when click the second image will do another action and so on for all images, I have it inside the view pager
thanks in advance.
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
ImageAdapter:
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.g,
R.drawable.h,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
intpadding=context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
To catch click events in ViewPager you have to override onTouchListener, since default implementation is not made to handle clicks
Your MainActivity should look something like this:
private ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager= (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
mViewPager.setAdapter(adapter);
final GestureDetector tapGestureDetector = new GestureDetector(this, new TapGestureListener());
mViewPager.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
}
private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mViewPager.getCurrentItem() == 0) {
//do your thing tied with first page
} else if (mViewPager.getCurrentItem() == 1) {
//do your thing tied with second page
} else if (mViewPager.getCurrentItem() == 2) {
//do your thing tied with third page
}
return super.onSingleTapConfirmed(e);
}
}
Try this:
#Override
public Object instantiateItem(View collection, final int pos) { //have
to make final so we can see it inside of onClick()
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.YOUR_PAGE, null);
page.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//this will log the page number that was click do your action
according to position
Log.i("TAG", "This page was clicked: " + pos);
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
I have a GridViewActivity, GridViewAdapter, FullScreenActivity and FullScreenImageAdapter. When I click Image from GridView, go to FullScreenActivity and it doesn't show nothing. I also test from Drawable imgDisplay.setImageResource(R.drawable.a); It doesn't happen. What wrong? How can I solve? Please!
In GridViewAdapter; Image Click Listener,
private class OnImageClickListener implements View.OnClickListener {
int _postion;
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
Intent i = new Intent(_activity, FullScreenActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
In FullScreenActivity; get position from GridView, and then I create new FullScreenImageAdapter
List<Item> mItems = new ArrayList<>();
int position = getIntent().getIntExtra("position", 0);
Log.i("Result", String.valueOf(position)); // return 0,1,2,3.. etc
adapter = new FullScreenImageAdapter(FullScreenActivity.this, mItems);
viewPager.setAdapter(adapter);
In FullScreenImageAdapter;
public class FullScreenImageAdapter extends PagerAdapter {
List<Item> mItems = new ArrayList<>();
Activity _activity;
LayoutInflater inflater;
public FullScreenImageAdapter(Activity activity, List<Item> mItems) {
this._activity = activity;
this.mItems = mItems;
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
inflater = (LayoutInflater) _activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container, false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
imgDisplay.setImageResource(R.drawable.a); // want to show from mItems List
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
The ImageAdapter Class
public class ImageAdapter extends PagerAdapter implements AdapterView.OnItemClickListener {
Context context;
private int[] GalImages = new int[] {//array storing all images used in the 'slideshow' in the main menu
R.drawable.savedpageex,
R.drawable.ic_cdi_icon,
R.drawable.savedpageex,
R.drawable.ic_cdi_icon
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(R.dimen.abc_panel_menu_list_width);
imageView.setPadding(1, 1, 1, 1);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int clickedImage = GalImages[position];
}
}
In the MainActivity
ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
ImageAdapter adapter = new ImageAdapter(this);
wrappedAdapter = new InfinitePagerAdapter(adapter);
viewPager.setAdapter(wrappedAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
}
});
Right now, the pictures show up and they loop, I do need help getting the pictures to 'slide' at set time intervals, but the main issue is with setting up onClickListeners for each 'page'. Any help/advice?
You could add a switch statement inside of the onClickListener like this
switch(viewPager.getCurrentItem()){
case 0:
//stuff for first page
break;
case 1:
//stuff for second page
break;
}
...... etc.
or add a state to the viewpager to describe which "page" it is showing
and using that information do different things in the onClickListener
Animating a shared element transition between two fragments seems to be a pain. I have it working elsewhere in my app with the exact same code.
here is my on click code inside a recyclerview adapter:
private void click(int position, ItemViewHolder holder){
final ItemDescription itemDescription = itemListFiltered.get(position);
FragmentManager fm = mContext.getSupportFragmentManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && itemDescription != null) {
//animate transition
TransitionSet transitionSet = new TransitionSet();
transitionSet.addTransition(new ChangeTransform());
transitionSet.addTransition(new ChangeBounds());
transitionSet.addTransition(new ChangeImageTransform());
transitionSet.setDuration(300);
//set up fragment
ScanDetailsFragment frag = ScanDetailsFragment.newInstance(itemDescription, holder.productImage.getTransitionName());
frag.setEnterTransition(transitionSet);
frag.setExitTransition(transitionSet);
fm.beginTransaction().replace(R.id.fragment_container, frag)
.addSharedElement(holder.productImage, "product_image")
.addToBackStack("item details")
.commit();
}else {
ScanDetailsFragment itemDetails = ScanDetailsFragment.newInstance(itemDescription);
fm.beginTransaction().replace(R.id.fragment_container, itemDetails).addToBackStack("item details").commit();
}
I just can't seem to get this animation to work.
here is how I did it
Fragment with the RecyclerView
public class DogFragment extends Fragment implements DogAdapter.OnItemCLickListener {
public static final String TAG = "DogFragment";
#InjectView(R.id.recyclerview_dog)
RecyclerView mRecyclerView;
DogAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View v = inflater.inflate(R.layout.fragment_dog, container, false);
ButterKnife.inject(this, v);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final List<Integer> images = new ArrayList<>();
images.add(R.drawable.dog1);
images.add(R.drawable.dog2);
images.add(R.drawable.dog3);
final RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(layoutManager);
adapter = new DogAdapter(images);
adapter.setOnItemClickListener(this);
mRecyclerView.setAdapter(adapter);
}
public String getTAG() {
return TAG;
}
#Override
public void onItemClick(int position, int imageRefId, ImageView imageView) {
SingleDogFragment fragment = SingleDogFragment.getInstance(getActivity(), adapter.getImageTransitionName(getActivity(), position), imageRefId);
getFragmentManager().beginTransaction()
.addSharedElement(imageView, adapter.getImageTransitionName(getActivity(), position))
.replace(R.id.container, fragment, fragment.getTag())
.addToBackStack(null)
.commit();
}
}
The adapter
public class DogAdapter extends RecyclerView.Adapter<DogAdapter.ViewHolder> {
private OnItemCLickListener mItemClickListener;
private List<Integer> mImages;
public DogAdapter(List<Integer> images) {
mImages = images;
}
public int getItem(int position) {
return mImages.get(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.gridview_element_dog, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.mImageView.setImageResource(getItem(i));
viewHolder.mImageView.setTransitionName(
getImageTransitionName(viewHolder.mImageView.getContext(), i)
);
}
public String getImageTransitionName(Context context, int position) {
return context.getString(R.string.dog_transition_name) + position;
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#InjectView(R.id.dog_imageview)
ImageView mImageView;
public ViewHolder(final View view) {
super(view);
ButterKnife.inject(this, view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(getPosition(), getItem(getPosition()), mImageView);
}
}
}
public interface OnItemCLickListener {
public void onItemClick(int position, int refId, ImageView imageView);
}
public void setOnItemClickListener(final OnItemCLickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
Target fragment
public class SingleDogFragment extends Fragment {
private static final String ARG_TRANSITION_NAME = "ARG_TRANSITION_NAME";
private static final String ARG_IMAGE_REF_ID = "ARG_IMAGE_REF_ID";
#InjectView(R.id.single_dog_imageview)
ImageView mDogImage;
public static SingleDogFragment getInstance(Context context, String transitionName, int imageRefId) {
SingleDogFragment fragment = new SingleDogFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_TRANSITION_NAME, transitionName);
bundle.putInt(ARG_IMAGE_REF_ID, imageRefId);
fragment.setSharedElementEnterTransition(TransitionInflater.from(context).inflateTransition(R.transition.change_transform));
fragment.setEnterTransition(TransitionInflater.from(context).inflateTransition(R.transition.slide_left));
fragment.setExitTransition(TransitionInflater.from(context).inflateTransition(R.transition.slide_left));
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_single_dog, container, false);
ButterKnife.inject(this, v);
mDogImage.setTransitionName(getArguments().getString(ARG_TRANSITION_NAME));
mDogImage.setImageResource(getArguments().getInt(ARG_IMAGE_REF_ID));
return v;
}
}
change_transform.xml
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground"/>
<target android:excludeId="#android:id/navigationBarBackground"/> <!-- exclude the status bar and the navigation bar of the animation -->
</targets>
<changeBounds/>
<changeTransform/>
</transitionSet>
And here is what it look like
Hope I could help !