I am trying to swipe a row in my ListView, identify its text and perform certain actions. I am able to detect left/right swipes but how to I go about identifying the text for that swiped row? I am not able to identify its location unlike using onItemClickListener where I could use the position variable.
MainActivity Class
ListView orderListView;
ArrayList<String> orders;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_stock);
orderListView = (ListView)findViewById(R.id.orderListView);
orders = new ArrayList<>();
orders.add("order 1");
orders.add("order 2");
orders.add("order 3");
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, orders);
orderListView.setAdapter(adapter);
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(this, orderListView);
orderListView.setOnTouchListener(onSwipeTouchListener);
}
OnSwipeTouchListener Class
public class OnSwipeTouchListener implements View.OnTouchListener {
ListView list;
private GestureDetector gestureDetector;
private Context context;
public OnSwipeTouchListener(Context ctx, ListView list) {
gestureDetector = new GestureDetector(ctx, new GestureListener());
context = ctx;
this.list = list;
}
public OnSwipeTouchListener() {
super();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
public void onSwipeRight(int pos) {
Log.i("zxR", "right");
}
public void onSwipeLeft() {
Log.i("zxL", "left");
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
private int getPostion(MotionEvent e1) {
return list.pointToPosition((int) e1.getX(), (int) e1.getY());
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight(getPostion(e1));
else
onSwipeLeft();
return true;
}
return false;
}
}
}
Try this, I think this might help:
Include ArrayAdapter in the argument of the constructor of OnSwipeTouchListener and pass the adapter of the ListView from the main activity
Then add this code to your onFling()
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
int id = list.pointToPosition((int) e1.getX(), (int) e1.getY());
String text=adapter.getItem(id);
Toast.makeText(context,"Text:"+text,Toast.LENGTH_SHORT).show();
Use the new RecyclerView instead of ListView as it have simple api for gestures and animations.
The same question for RecyclerView:
https://stackoverflow.com/a/30601554/2627680
Related
Hi I'm new in android and recently I made a carousel with viewpager using this and it works fine with full width height images but when i resize images it doesn't work properly by that I mean it takes the entire width of the screen instead of specified width.
The actual idea is to have a carousel at the bottom of the page with small images.
So this is where I'm stuck and need some help actually I don't have much idea about this so I would appreciate some help.
Thank you
My code are below as follows
CarouselTransformer.class
public class CarouselEffectTransformer implements ViewPager.PageTransformer {
private int maxTranslateOffsetX;
private ViewPager viewPager;
public CarouselEffectTransformer(Context context) {
this.maxTranslateOffsetX = dp2px(context, 180);
}
public void transformPage(View view, float position) {
if (viewPager == null) {
viewPager = (ViewPager) view.getParent();
}
int leftInScreen = view.getLeft() - viewPager.getScrollX();
int centerXInViewPager = leftInScreen + view.getMeasuredWidth() / 2;
int offsetX = centerXInViewPager - viewPager.getMeasuredWidth() / 2;
float offsetRate = (float) offsetX * 0.38f / viewPager.getMeasuredWidth();
float scaleFactor = 1 - Math.abs(offsetRate);
if (scaleFactor > 0) {
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
view.setTranslationX(-maxTranslateOffsetX * offsetRate);
//ViewCompat.setElevation(view, 0.0f);
}
ViewCompat.setElevation(view, scaleFactor);
}
/**
* Dp to pixel conversion
*/
private int dp2px(Context context, float dipValue) {
float m = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * m + 0.5f);
}
}
PagerAdapter
public class MyPagerAdapter extends PagerAdapter{
Context context;
int adapterType;
ArrayList<NearbyDataProvider> arrayList = new ArrayList<>();
public MyPagerAdapter(Context context,ArrayList<NearbyDataProvider> arrayList, int adapterType) {
this.context = context;
this.arrayList = arrayList;
this.adapterType=adapterType;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.item_cover, null);
try {
NearbyDataProvider nearbyDataProvider = arrayList.get(position);
LinearLayout linMain = (LinearLayout) view.findViewById(R.id.linMain);
RoundedImageView imageCover = (RoundedImageView) view.findViewById(R.id.imageCover);
CustomTextViewMedium customTextViewMedium = (CustomTextViewMedium)view.findViewById(R.id.imageTitle);
CustomTextViewMedium customTextViewMedium1 =(CustomTextViewMedium)view.findViewById(R.id.imageContent);
linMain.setTag(position);
switch (adapterType)
{
case NearbyFragment.ADAPTER_TYPE_TOP:
break;
case NearbyFragment.ADAPTER_TYPE_BOTTOM:
linMain.setBackgroundResource(0);
break;
}
GlideApp.with(context)
.load(arrayList.get(position).getImage())
.into(imageCover);
customTextViewMedium.setText(nearbyDataProvider.getPlace());
container.addView(view);
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return (view == object);
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
I want to get vertical scrolling (one item at a time) but can't find they way to implement viewpager on my code. can anyone help me in implementing view pager on my code. I tried using Fragment for getting vertical scroll but no luck. Any help will be appreciated. Thanks in advance.
Here is my code,
MainActivity -
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
songAdapter = new SongAdapter(this, _songs);
recyclerView.setAdapter(songAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
#Override
public void onItemClick(final Button b, View view, final SongInfo obj, int position) {
if (b.getText().equals("Stop")) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
b.setText("Play");
} else {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
Log.d("Prog", "run: " + mediaPlayer.getDuration());
}
});
b.setText("Stop");
} catch (Exception e) {
}
}
};
myHandler.postDelayed(runnable, 100);
}
}
});
checkUserPermission();
Thread t = new runThread();
t.start();
}
public class runThread extends Thread {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Runwa", "run: " + 1);
if (mediaPlayer != null) {
seekBar.post(new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
});
Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
}
}
}
}
private void checkUserPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
return;
}
}
//getMp3Songs();
loadSongs();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 123:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//getMp3Songs();
loadSongs();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void loadSongs() {
Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
// Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Log.i("DATA111", url);
mediaMetadataRetrieve = new MediaMetadataRetriever();
mediaMetadataRetrieve.setDataSource(url);
art = mediaMetadataRetrieve.getEmbeddedPicture();
if (art != null) {
songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
}
SongInfo s = new SongInfo(name, artist, url, songImage);
_songs.add(s);
} while (cursor.moveToNext());
}
cursor.close();
songAdapter = new SongAdapter(MainActivity.this, _songs);
}
}
}
SongAdapter -
private ArrayList<SongInfo> _songs = new ArrayList<SongInfo>();
private Context context;
private OnItemClickListener mOnItemClickListener;
public SongAdapter(Context context, ArrayList<SongInfo> songs) {
this.context = context;
this._songs = songs;
}
public interface OnItemClickListener {
void onItemClick(Button b, View view, SongInfo obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
#Override
public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View myView = LayoutInflater.from(context).inflate(R.layout.row_songs, viewGroup, false);
return new SongHolder(myView);
}
#Override
public void onBindViewHolder(final SongHolder songHolder, final int i) {
final SongInfo s = _songs.get(i);
songHolder.tvSongName.setText(_songs.get(i).getSongname());
songHolder.tvSongArtist.setText(_songs.get(i).getArtistname());
songHolder.tvAlbum_art.setImageBitmap(_songs.get(i).getThaImage());
songHolder.btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(songHolder.btnAction, v, s, i);
}
}
});
}
#Override
public int getItemCount() {
return _songs.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView tvSongName, tvSongArtist;
Button btnAction;
ImageView tvAlbum_art;
public SongHolder(View itemView) {
super(itemView);
tvSongName = (TextView) itemView.findViewById(R.id.tvSongName);
tvSongArtist = (TextView) itemView.findViewById(R.id.tvArtistName);
tvAlbum_art = (ImageView) itemView.findViewById(R.id.album_art);
btnAction = (Button) itemView.findViewById(R.id.button_action);
}
}
}
VerticalViewPager -
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
this(context, null);
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
#Override
public boolean canScrollHorizontally(int direction) {
return false;
}
#Override
public boolean canScrollVertically(int direction) {
return super.canScrollHorizontally(direction);
}
private void init() {
setPageTransformer(true, new VerticalPageTransformer());
setOverScrollMode(View.OVER_SCROLL_NEVER);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final boolean toIntercept = super.onInterceptTouchEvent(flipXY(ev));
flipXY(ev);
return toIntercept;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
final boolean toHandle = super.onTouchEvent(flipXY(ev));
flipXY(ev);
return toHandle;
}
private MotionEvent flipXY(MotionEvent ev) {
final float width = getWidth();
final float height = getHeight();
final float x = (ev.getY() / height) * width;
final float y = (ev.getX() / width) * height;
ev.setLocation(x, y);
return ev;
}
private static final class VerticalPageTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
final int pageWidth = view.getWidth();
final int pageHeight = view.getHeight();
if (position < -1) {
view.setAlpha(0);
} else if (position <= 1) {
view.setAlpha(1);
view.setTranslationX(pageWidth * -position);
float yPosition = position * pageHeight;
view.setTranslationY(yPosition);
} else {
view.setAlpha(0);
}
}
}
}
Start with this simple example:
1) MnnnnnActivity.class:----------
public class MnnnnnActivity extends AppCompatActivity {
private VerticalViewPager vp;
private MPagerAdapter mPagerAdapter;
private int lastPage = 0;
private List<String> songs = new ArrayList<String>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout5);
vp = (VerticalViewPager) findViewById(R.id.vp);
for(int i = 0 ; i<10 ; i++){
songs.add(i , "song " + i);
}
mPagerAdapter = new MPagerAdapter(getApplicationContext(), songs);
vp.setAdapter(mPagerAdapter);
vp.setOffscreenPageLimit(1);
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(lastPage > position){ //left
}else{ // right
}
lastPage = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
2) MPagerAdapter.class:-----
public class MPagerAdapter extends PagerAdapter {
private Context mContext;
private List<String> songs = new ArrayList<String>();
public MPagerAdapter(Context context , List<String> songs) {
mContext = context;
this.songs = songs;
}
#Override
#NonNull
public Object instantiateItem(#NonNull final ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View layout = (View) inflater.inflate(R.layout.layout_list, collection, false);
TextView tv = (TextView) layout.findViewById(R.id.tv_song);
tv.setText(songs.get(position));
Button b = (Button) layout.findViewById(R.id.b_song);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext , "Play " + songs.get(position) , Toast.LENGTH_LONG).show();
}
});
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return songs.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return songs.get(position);
}
}
3) VerticalViewPager.class:-------
//https://stackoverflow.com/questions/13477820/android-vertical-viewpager
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
super(context);
init();
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new VerticalPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev);
//https://stackoverflow.com/questions/15365915/viewpager-nested-in-viewpager
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
this.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_DOWN:
this.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
this.getParent().requestDisallowInterceptTouchEvent(true);
break;
}
return intercepted;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
}
4) VerticalPageTransformer.class:-----------
//https://stackoverflow.com/questions/13477820/android-vertical-viewpager
public class VerticalPageTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 1) { // [-1,1]
view.setAlpha(1);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
//set Y position to swipe in from top
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
5) layout5.xml:--------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.admin.accessories.VerticalViewPager
android:id="#+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.admin.accessories.VerticalViewPager>
</android.support.constraint.ConstraintLayout>
6) layout_list.xml:--------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="SName"
android:layout_marginBottom="20dp"
android:id="#+id/tv_song"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Play"
android:id="#+id/b_song"/>
</LinearLayout>
7) Output:---------
Simple solution is try rotating viewpager and its child view
mViewPager.setRotation(90);
It will rotate view pager and it's child views as well. Now rotate child view again in opposite direction.
childView.setRotation(270);
I am building a list that had to be able to reorder the item's position.
Fortunately for me, I've found an external library which has exactly what I needed.
Unfortunately, I could not implement a delete item action using onContextItemSelected() because menuInfo keeps always returning null, so I cannot read the position of selected item I wish to delete.
This user blog post gave a solution by overriding getContextMenuInfo().
If item.getMenuInfo() is null in onContextItemSelected(MenuItem item) method, I guess you are using custom ListView or GridView instead of android default ones. In such case, your custom View is not implementing getContextMenuInfo() method. Don’t worry we can fix that if you have its source. Open the view file and override the method getContextMenuInfo().
I have tried this in many ways, but it seems I am doing things wrong.
Is this the only solution or am I missing something?
Activity
public class SurveyAdd extends AppCompatActivity {
private ArrayList<Pair<Long, String>> mItemArray = new ArrayList<>();
private DragListView mDragListView;
ItemAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey_add);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDragListView = (DragListView) findViewById(R.id.surveyadd_list);
mDragListView.getRecyclerView().setVerticalScrollBarEnabled(true);
mDragListView.setDragListListener(new DragListView.DragListListener() {
#Override
public void onItemDragStarted(int position) {
}
#Override
public void onItemDragEnded(int fromPosition, int toPosition) {
if (fromPosition != toPosition) {
setSurveyChange(true);
}
}
});
mDragListView.setCanDragHorizontally(false);
mDragListView.setCustomDragItem(new MyDragItem(context, R.layout.item_survey_add));
mDragListView.setLayoutManager(new LinearLayoutManager(context));
mDragListView.setLayoutManager(new LinearLayoutManager(context));
ItemAdapter listAdapter = new ItemAdapter(mItemArray, R.layout.item_survey_add, R.id.item_add_image_button, false);
mDragListView.setAdapter(listAdapter, true);
registerForContextMenu(mDragListView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_survey_add_item, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.surveyadd_action_delete:
if (item.getMenuInfo() == null) {
Toast.makeText(SurveyAdd.this, "NULL", Toast.LENGTH_SHORT).show();
}
int position = info.position; // CAN'T USE THIS, ALWAYS THROWS NULLPOINTEREXCEPTION
Toast.makeText(SurveyAdd.this, "" + position, Toast.LENGTH_SHORT).show();
return true;
}
}
}
// The activity was simplified for posting
ItemAdapter
imported and edited class
public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder> {
private int mLayoutId;
private int mGrabHandleId;
public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
super(dragOnLongPress);
mLayoutId = layoutId;
mGrabHandleId = grabHandleId;
setHasStableIds(true);
setItemList(list);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(mLayoutId, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
String text = mItemList.get(position).second;
String[] separated = text.split("::");
holder.mText.setText(separated[1]);
holder.itemView.setTag(text);
}
#Override
public long getItemId(int position) {
return mItemList.get(position).first;
}
public class ViewHolder extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>.ViewHolder {
public TextView mText;
public ImageView mIcon;
public ViewHolder(final View itemView) {
super(itemView, mGrabHandleId);
mText = (TextView) itemView.findViewById(R.id.item_add_question);
mIcon = (ImageView) itemView.findViewById(mGrabHandleId);
}
#Override
public void onItemClicked(View view) {
}
#Override
public boolean onItemLongClicked(View view) {
return false;
}
}
}
DragListView
imported and locked class
public class DragListView extends FrameLayout {
public interface DragListListener {
void onItemDragStarted(int position);
void onItemDragEnded(int fromPosition, int toPosition);
}
private DragItemRecyclerView mRecyclerView;
private DragListListener mDragListListener;
private DragItem mDragItem;
private boolean mDragEnabled = true;
private float mTouchX;
private float mTouchY;
public DragListView(Context context) {
super(context);
}
public DragListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DragListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
mDragItem = new DragItem(getContext());
mRecyclerView = createRecyclerView();
mRecyclerView.setDragItem(mDragItem);
addView(mRecyclerView);
addView(mDragItem.getDragItemView());
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean retValue = handleTouchEvent(event);
return retValue || super.onInterceptTouchEvent(event);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean retValue = handleTouchEvent(event);
return retValue || super.onTouchEvent(event);
}
private boolean handleTouchEvent(MotionEvent event) {
mTouchX = event.getX();
mTouchY = event.getY();
if (isDragging()) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
mRecyclerView.onDragging(event.getX(), event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mRecyclerView.onDragEnded();
break;
}
return true;
}
return false;
}
private DragItemRecyclerView createRecyclerView() {
final DragItemRecyclerView recyclerView = (DragItemRecyclerView) LayoutInflater.from(getContext()).inflate(R.layout.drag_item_recycler_view, this, false);
recyclerView.setMotionEventSplittingEnabled(false);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setVerticalScrollBarEnabled(false);
recyclerView.setHorizontalScrollBarEnabled(false);
recyclerView.setDragItemListener(new DragItemRecyclerView.DragItemListener() {
private int mDragStartPosition;
#Override
public void onDragStarted(int itemPosition, float x, float y) {
getParent().requestDisallowInterceptTouchEvent(true);
mDragStartPosition = itemPosition;
if (mDragListListener != null) {
mDragListListener.onItemDragStarted(itemPosition);
}
}
#Override
public void onDragging(int itemPosition, float x, float y) {
}
#Override
public void onDragEnded(int newItemPosition) {
if (mDragListListener != null) {
mDragListListener.onItemDragEnded(mDragStartPosition, newItemPosition);
}
}
});
return recyclerView;
}
public RecyclerView getRecyclerView() {
return mRecyclerView;
}
public DragItemAdapter getAdapter() {
if (mRecyclerView != null) {
return (DragItemAdapter) mRecyclerView.getAdapter();
}
return null;
}
public void setAdapter(DragItemAdapter adapter, boolean hasFixedItemSize) {
mRecyclerView.setHasFixedSize(hasFixedItemSize);
mRecyclerView.setAdapter(adapter);
adapter.setDragEnabled(mDragEnabled);
adapter.setDragStartedListener(new DragItemAdapter.DragStartedListener() {
#Override
public void onDragStarted(View itemView, long itemId) {
mRecyclerView.onDragStarted(itemView, itemId, mTouchX, mTouchY);
}
});
}
public void setLayoutManager(RecyclerView.LayoutManager layout) {
mRecyclerView.setLayoutManager(layout);
}
public void setDragListListener(DragListListener listener) {
mDragListListener = listener;
}
public boolean isDragEnabled() {
return mDragEnabled;
}
public void setDragEnabled(boolean enabled) {
mDragEnabled = enabled;
if (mRecyclerView.getAdapter() != null) {
((DragItemAdapter) mRecyclerView.getAdapter()).setDragEnabled(mDragEnabled);
}
}
public void setCustomDragItem(DragItem dragItem) {
removeViewAt(1);
DragItem newDragItem;
if (dragItem != null) {
newDragItem = dragItem;
} else {
newDragItem = new DragItem(getContext());
}
newDragItem.setCanDragHorizontally(mDragItem.canDragHorizontally());
newDragItem.setSnapToTouch(mDragItem.isSnapToTouch());
mDragItem = newDragItem;
mRecyclerView.setDragItem(mDragItem);
addView(mDragItem.getDragItemView());
}
public boolean isDragging() {
return mRecyclerView.isDragging();
}
public void setCanDragHorizontally(boolean canDragHorizontally) {
mDragItem.setCanDragHorizontally(canDragHorizontally);
}
public void setSnapDragItemToTouch(boolean snapToTouch) {
mDragItem.setSnapToTouch(snapToTouch);
}
public void setCanNotDragAboveTopItem(boolean canNotDragAboveTop) {
mRecyclerView.setCanNotDragAboveTopItem(canNotDragAboveTop);
}
public void setScrollingEnabled(boolean scrollingEnabled) {
mRecyclerView.setScrollingEnabled(scrollingEnabled);
}
}
This is an old post but i figured it out using that same draglistview.
Im using Xamarin but it's close enough to the same. Just type the C# in Java as necessary:
protected override IContextMenuContextMenuInfo ContextMenuInfo
{
get
{
IContextMenuContextMenuInfo menuInfo = base.ContextMenuInfo;
if (menuInfo == null)
{
IListAdapter adapter = Adapter;
int pos = GetPositionForView(selectedView);
menuInfo = new AdapterContextMenuInfo(selectedView, pos, adapter.GetItemId(pos));
}
return menuInfo;
}
}
public void OnLongPress(MotionEvent e){
int position = PointToPosition(mDownX, mDownY);
int itemNum = position - FirstVisiblePosition;
selectedView = GetChildAt(itemNum); //class variable
...
}
I am using SwipeableRecyclerView and I was wondering how I can disable left swipe?
This is my code:
MainActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.github.brnunes.swipeablerecyclerview.SwipeableRecyclerViewTouchListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private CardViewAdapter mAdapter;
private ArrayList<String> mItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<>(30);
for (int i = 0; i < 30; i++) {
mItems.add(String.format("Card number %02d", i));
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Tapped " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton1Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button1 in " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton2Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button2 in " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
};
mAdapter = new CardViewAdapter(mItems, itemTouchListener);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
/**
* Interface for the touch events in each item
*/
public interface OnItemTouchListener {
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton2Click(View view, int position);
}
/**
* A simple adapter that loads a CardView layout with one TextView and two Buttons, and
* listens to clicks on the Buttons or on the CardView
*/
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
private List<String> cards;
private OnItemTouchListener onItemTouchListener;
public CardViewAdapter(List<String> cards, OnItemTouchListener onItemTouchListener) {
this.cards = cards;
this.onItemTouchListener = onItemTouchListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.title.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards == null ? 0 : cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private Button button1;
private Button button2;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.card_view_title);
button1 = (Button) itemView.findViewById(R.id.card_view_button1);
button2 = (Button) itemView.findViewById(R.id.card_view_button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onButton1Click(v, getPosition());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onButton2Click(v, getPosition());
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onCardViewTap(v, getPosition());
}
});
}
}
}
}
SwipeableRecyclerViewTouchListener.class
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A {#link View.OnTouchListener} that makes the list items in a {#link android.support.v7.widget.RecyclerView}
* dismissable by swiping.
* <p/>
* <p>Example usage:</p>
* <p/>
* <pre>
* SwipeDismissRecyclerViewTouchListener touchListener =
* new SwipeDismissRecyclerViewTouchListener(
* listView,
* new SwipeDismissRecyclerViewTouchListener.OnDismissCallback() {
* public void onDismiss(ListView listView, int[] reverseSortedPositions) {
* for (int position : reverseSortedPositions) {
* adapter.remove(adapter.getItem(position));
* }
* adapter.notifyDataSetChanged();
* }
* });
* listView.setOnTouchListener(touchListener);
* listView.setOnScrollListener(touchListener.makeScrollListener());
* </pre>
* <p/>
* <p>This class Requires API level 12 or later due to use of {#link
* android.view.ViewPropertyAnimator}.</p>
*/
public class SwipeableRecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private RecyclerView mRecyclerView;
private SwipeListener mSwipeListener;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<>();
private int mDismissAnimationRefCount = 0;
private float mAlpha;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private int mAnimatingPosition = ListView.INVALID_POSITION;
private View mDownView;
private boolean mPaused;
private float mFinalDelta;
/**
* Constructs a new swipe touch listener for the given {#link android.support.v7.widget.RecyclerView}
*
* #param recyclerView The recycler view whose items should be dismissable by swiping.
* #param listener The listener for the swipe events.
*/
public SwipeableRecyclerViewTouchListener(RecyclerView recyclerView, SwipeListener listener) {
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = recyclerView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mRecyclerView = recyclerView;
mSwipeListener = listener;
/**
* This will ensure that this SwipeableRecyclerViewTouchListener is paused during list view scrolling.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener.
*/
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
setEnabled(newState != RecyclerView.SCROLL_STATE_DRAGGING);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
});
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* #param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent motionEvent) {
return handleTouchEvent(motionEvent);
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent motionEvent) {
handleTouchEvent(motionEvent);
}
private boolean handleTouchEvent(MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mRecyclerView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
break;
}
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mRecyclerView.getChildCount();
int[] listViewCoords = new int[2];
mRecyclerView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mRecyclerView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null && mAnimatingPosition != mRecyclerView.getChildPosition(mDownView)) {
mAlpha = mDownView.getAlpha();
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
mDownPosition = mRecyclerView.getChildPosition(mDownView);
if (mSwipeListener.canSwipe(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null && mSwiping) {
// cancel
mDownView.animate()
.translationX(0)
.alpha(mAlpha)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
mFinalDelta = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(mFinalDelta) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = mFinalDelta > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (mFinalDelta < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss && mDownPosition != mAnimatingPosition && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
final View downView = mDownView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
mAnimatingPosition = mDownPosition;
mDownView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(mAlpha)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (!mSwiping && Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
}
if (mSwiping) {
mDownView.setTranslationX(deltaX - mSwipingSlop);
mDownView.setAlpha(Math.max(0f, Math.min(mAlpha,
mAlpha * (1f - Math.abs(deltaX) / mViewWidth))));
return true;
}
break;
}
}
return false;
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalLayoutParamsHeight = lp.height;
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
if (mFinalDelta > 0) {
mSwipeListener.onDismissedBySwipeRight(mRecyclerView, dismissPositions);
} else {
mSwipeListener.onDismissedBySwipeLeft(mRecyclerView, dismissPositions);
}
// Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
// animation with a stale position
mDownPosition = ListView.INVALID_POSITION;
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(mAlpha);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalLayoutParamsHeight;
pendingDismiss.view.setLayoutParams(lp);
}
// Send a cancel event
long time = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(time, time,
MotionEvent.ACTION_CANCEL, 0, 0, 0);
mRecyclerView.dispatchTouchEvent(cancelEvent);
mPendingDismisses.clear();
mAnimatingPosition = ListView.INVALID_POSITION;
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
/**
* The callback interface used by {#link SwipeableRecyclerViewTouchListener} to inform its client
* about a swipe of one or more list item positions.
*/
public interface SwipeListener {
/**
* Called to determine whether the given position can be swiped.
*/
boolean canSwipe(int position);
/**
* Called when the item has been dismissed by swiping to the left.
*
* #param recyclerView The originating {#link android.support.v7.widget.RecyclerView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions);
/**
* Called when the item has been dismissed by swiping to the right.
*
* #param recyclerView The originating {#link android.support.v7.widget.RecyclerView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions);
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(#NonNull PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
}
Use simple recyclerView and then You can use ItemTouchHelper.Callback
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final YourAdapter mAdapter;
public SimpleItemTouchHelperCallback(YourAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return true;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
In YourAdapter class which is extending recyclerview adapter add these functions.
public void onItemMove(int oldPosition, int newPosition) {
notifyItemMoved(oldPosition,newPosition);
}
public void onItemDismiss(int adapterPosition) {
/// here you can delete from the array and notify for that specific position
}
ItemTouchHelper provides some flags which you can see here
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
If you want to disable Left to Right Swipe just remove ItemTouchHelper.START flag.
If you want to disable Right to Left Swipe just remove ItemTouchHelper.END flag.
You can pass 0 value instead of swipeFlags. Swipe will not work.
Same goes for dragFlags.
I have implemented this as well and it works like a charm ;) Happy Coding <3
I create android app with notification.
Is exist any way for programatically determine user's gestures (horizontal and vertical swypes) on my notification?
Try using following code you can apply swiping gestures to ListView.
public class NotificationsFragment extends Fragment {
ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mContext = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mOnTouchListener = new MyTouchListener();
view = inflater.inflate(R.layout.fragment_notification, container, false);
mListView = (ListView) view.findViewById(R.id.notification_list);
notificationtypeList = new ArrayList<String>();
mListView.setOnTouchListener(new OnSwipeTouchListener(mContext));
return view;
}
/**
* Detects left and right swipes across a view.
*/
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
int id = mListView.pointToPosition((int) e1.getX(), (int) e1.getY());
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
return true;
}
return false;
}
return listviewElementsheight;
}
}