Disable ViewPager Swipe From Right To Left and Left To Right Side - java

I am using ViewPager in one of my android application. I am learning yet Android and so does not know much about it. I want disable swipe from left to right and right to left on position based. I have searched in stackoverflow for solution but not got any proper solution. I am attaching my code here. Let me know if someone can help me to solve this puzzle.
My ViewPager
adapter = new MyAdapter(getSupportFragmentManager());
viewPager.setOffscreenPageLimit(0);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
constant.new_ad_count = constant.new_ad_count + 1;
mItemIndx = position;
try {
int index = position % ITEMS_PER_PAGE;
currentQuote = quotes.get(index);
} catch
(Exception e) {
}
mPageIndx = ((position + 1) / ITEMS_PER_PAGE) + (((position + 1) % ITEMS_PER_PAGE) > 0 ? 1 : 0);
updateUI();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(mItemIndx);
updateUI();
}
Function From Which I want Disable Swipe
private void updateUI() {
lblLikeCount.setText(currentQuote.getQuLike());
lblShareCount.setText(currentQuote.getQuShare());
lblTime.setText(currentQuote.getQuTime());
textPageCount.setText((mItemIndx + 1) + " / " + totalSize);
// butNext.setVisibility((mItemIndx < totalSize - 1) ? View.VISIBLE : View.INVISIBLE);
butPrev.setVisibility((mItemIndx > 0) ? View.VISIBLE : View.INVISIBLE);
if(mItemIndx==totalSize-1||(mItemIndx+1)%ITEMS_PER_PAGE==0) {
butNext.setVisibility(View.INVISIBLE);
//I want Disable Right to Left Swipe Here
} else {
butNext.setVisibility(View.VISIBLE);
}
if (mItemIndx-1<0 ||(mItemIndx)%ITEMS_PER_PAGE==0) {
butPrev.setVisibility(View.INVISIBLE);
//I want Disable Left to Right Here
} else {
butPrev.setVisibility(View.VISIBLE);
}
}
Thanks a lot Friends :)

Use a this NonSwipableViewPager class, using this, you will only be able to change the page when calling setCurrentItem.
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
setMyScroller();
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setMyScroller();
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
//down one is added for smooth scrolling
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
Add this class to your project, then in the layout where you want it, replace ViewPager with:
<yourpackagename.NonSwipeableViewPager
Then initialise it in your Activity or Fragment:
NonSwipeableViewPager pager = (NonSwipeableViewPager) findViewById(R.id.pager);

Related

Problem with drawing canvas line in scrollView

I'm trying to draw a scrollable timeline. I implement singleLine custom view for drawing a line between circle ImageView's of recycler view:
public class SingleLine extends View {
WeakReference<Context> ctx;
Paint paint;
PointF pointA, pointB;
private int height_custom;
public SingleLine(Context context) {
super(context);
ctx = new WeakReference<>(context);
init();
}
public SingleLine(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
ctx = new WeakReference<>(context);
init();
}
public void init() {
paint = new Paint();
pointA = new PointF();
pointB = new PointF();
paint.setStrokeWidth(10);
paint.setColor(ctx.get().getResources().getColor(R.color.green));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(pointA.x, pointA.y, pointB.x, pointB.y, paint);
invalidate();
}
public PointF getPointA() {return pointA;}
public void setPointA(PointF pointA) {this.pointA = pointA;}
public PointF getPointB() {return pointB;}
public void setPointB(PointF pointB) {this.pointB = pointB;}
}
And in onBindViewHolder() method of my adapter, I use an interface for measuring x/y coordinates of first and last visible view of recyclerview:
#Override
public void onBindViewHolder(#NonNull final TaskViewHolder holder, final int position) {
Tasks tasks = datalist_tasks.get(position);
String hour = "" + tasks.getHour() + ":" + tasks.getMinute();
holder.tv_clock.setText(hour);
holder.tv_title.setText(tasks.getTitle());
holder.tv_comment.setText(tasks.getComment());
holder.itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
holder.itemView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
holder.itemView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
if (iOnMeasureCustomView != null)
iOnMeasureCustomView.onMeasure(holder.iv_status, position);
}
});
}
And I implement that interface in my activity like below:
LinearLayoutManager layoutManager1 = new LinearLayoutManager(_C.get(), RecyclerView.VERTICAL, false);
rv_tasks.setLayoutManager(layoutManager1);
tasksAdapter.setiOnMeasureCustomView(new IOnMeasureCustomView() {
#Override
public void onMeasure(ImageView iv_status, int position) {
int[] screen = new int[2];
iv_status.getLocationOnScreen(screen);
int width = (int) ((iv_status.getWidth() / 2) + convertDpToPixel(8));
if (position == layoutManager1.findFirstCompletelyVisibleItemPosition()) {
pointA.set(iv_status.getX() + width, iv_status.getY() + convertDpToPixel(8));
}
else if (position == layoutManager1.findLastCompletelyVisibleItemPosition()) {
pointB.set(iv_status.getX() + width, screen[1] - convertDpToPixel(40));
singleLine.setPointA(pointA);
singleLine.setPointB(pointB);
singleLine.invalidate();
}
}
});
And also I implement addOnScrollListener() for my recyclerview and write this code snippet (I don't know that if this implementation is correct or no):
rv_tasks.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
PointF a = singleLine.getPointA();
PointF b = singleLine.getPointB();
if (dy > 0) {
a.y -= dy;
b.y -= dy;
singleLine.setPointA(a);
singleLine.setPointB(b);
singleLine.invalidate();
} else {
a.y += Math.abs(dy);
b.y += Math.abs(dy);
singleLine.setPointA(a);
singleLine.setPointB(b);
singleLine.invalidate();
}
}
});
My problem is when I scroll in activity, like the gif below, my singleLine is something like cutting off imageView and the end x/y of line become the x/y of end of the screen.
Questios
How can I set x/y of the line to prevent this?
And also I need some help with drawing this line with animation. How can I draw this line with animation that starts when the activity started?

How to recognize the last page of viewpager and automatically redirect to first page when swiped

My title is my problem, I have 3 pages in a viewPager. How do I redirect to first page when I swipe on the last page in viewPager?
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
int x = position;
Log.i("ON Possition",Integer.Tostring(x));
if(x == 3){
viewPager.setCurrentItem(x);
Log.i("ON last Possition",Integer.Tostring());
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
you can't move to first page smoothly from last page.
read below code. we should fake item count.
private class MyPagerAdapter extends PagerAdapter {
Context context;
public MyPagerAdapter(Context context) {
this.context= context;
}
#Override
public int getCount() {
if (tList != null && tList.size() > 1) {
return tList.size() * MAX_PAGE; // simulate infinite by big number of products
} else {
return tList.size();
}
}
#Override
public int getItemPosition(Object object) {
int position;
if (tList != null && tList.size() > 1) {
position = super.getItemPosition(object) % tList.size(); // use modulo for infinite cycling
return position;
} else {
return super.getItemPosition(object);
}
}
public int getItemPosition(int index) {
int position;
if (tList!= null && tList.size() > 1) {
position = index % tList.size(); // use modulo for infinite cycling
return position;
} else {
return index;
}
}
}

Snap HorizontalScrollView

I got the code below from here.
This code snaps the items of HorizontalScrollView. I tried a lot to implement this customView inside my layout but I am not able to figure out to how to attach my layout to it.
This example does add the views programmatically and calls them Features.
In XML I have done "my package name.view" but I cannot figure out how to call setFeatureItems so that my Views can be attached to it.
The snapping feature can be applied on RecyclerView easily by using SnapHelper but I haven't found anything for HorizontalScrollView.
public class HomeFeatureLayout extends HorizontalScrollView {
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private ArrayList mItems = null;
private GestureDetector mGestureDetector;
private int mActiveFeature = 0;
public HomeFeatureLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public HomeFeatureLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HomeFeatureLayout(Context context) {
super(context);
}
public void setFeatureItems(ArrayList items){
LinearLayout internalWrapper = new LinearLayout(getContext());
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.mItems = items;
for(int i = 0; i< items.size();i++){
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null);
//...
//Create the view for each screen in the scroll view
//...
internalWrapper.addView(featureLayout);
}
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//If the user swipes
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
int scrollX = getScrollX();
int featureWidth = v.getMeasuredWidth();
mActiveFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = mActiveFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else{
return false;
}
}
});
mGestureDetector = new GestureDetector(new MyGestureDetector());
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
} catch (Exception e) {
Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
}
return false;
}
}
}
in your recycleview adapter you will have reference to HomeFeatureLayout there you can call
homeFeatureLayout.setFeatureItems(items);
EDIT
public void setFeatureItems(ArrayList items){
for(int i = 0; i< items.size();i++){
// here you need to provide layout of individual items in your horizontal scrollview
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.anyLayout,null);
//...
//display information here
//...
TextView title = (TextView)featureLayout.findviewById(R.id.title);
title.setText("view title "+item.get(i).getTitle());
ImageView image = (ImageView)featureLayout.findviewById(R.id.icon);
image.setResourceId(R.drawable.icon);
internalWrapper.addView(featureLayout);
}
}

I create a RecyclerView in Fragment but while reloading data RecyclerView does not maintains state.

//I have created RecycleView in Fragment as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_shop, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
stackView = (RelativeLayout) view.findViewById(R.id.stack_view);
firstStack = (CustomImageView) view.findViewById(R.id.firstStack);
secondStack = (CustomImageView) view.findViewById(R.id.secondStack);
thirdStack = (CustomImageView) view.findViewById(R.id.thirdStack);
stackTopGap = view.findViewById(R.id.view);
new Handler().post(new Runnable() {
#Override
public void run() {
firstStack.getLayoutParams().width = stackView.getWidth() - 40;
secondStack.getLayoutParams().width = stackView.getWidth() - 80;
thirdStack.getLayoutParams().width = stackView.getWidth() - 120;
width = thirdStack.getLayoutParams().width;
recyclerView.getLayoutParams().height = recyclerView.getHeight() - (firstStack.getHeight() + stackTopGap.getHeight());
stackView.getLayoutParams().height = firstStack.getHeight();
}
});
recyclerView.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getActivity()) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
// A good idea would be to create this instance in some initialization method, and just set the target position in this method.
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
#Override
public PointF computeScrollVectorForPosition(int targetPosition) {
//int yDelta = calculateCurrentDistanceToPosition(targetPosition);
return new PointF(0, 200);
}
// This is the important method. This code will return the amount of time it takes to scroll 1 pixel.
// This code will request X milliseconds for every Y DP units.
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 7 / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7, displayMetrics);
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
final int positionView = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (dy > 0) {
if (positionView >= 2) {
final View view = recyclerView.getChildAt(2);
if (view != null && recyclerView.getChildAdapterPosition(view) == positionView) {
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 200, 0);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
if (counter == 0) {
if (recyclerView.getAdapter().getItemCount() - 4 >= positionView) {
createStackImageView();
}
if (stackView.getChildAt(1) != null) {
//stackView.getChildAt(1).setScaleX(1.5f);
}
counter++;
}
recyclerView.smoothScrollToPosition(positionView);
}
#Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
stackView.requestLayout();
stackView.removeView(stackView.getChildAt(1));
stackView.invalidate();
try {
for (int i = 1; i < 4; i++) {
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(positionView + i))
.into((ImageView) stackView.getChildAt(i));
}
} catch (IndexOutOfBoundsException | NullPointerException | IllegalArgumentException ex) {
ex.printStackTrace();
}
counter = 0;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setDuration(150);
view.setAnimation(translateAnimation);
}
}
for (int i = stackView.getChildCount() - 1; i >= 2; i--) {
ResizeAnimation resizeAnimation = new ResizeAnimation(stackView.getChildAt(i));
resizeAnimation.setHeights(stackView.getChildAt(i).getHeight(), stackView.getChildAt(i - 1).getHeight());
resizeAnimation.setWidths(stackView.getChildAt(i).getWidth(), stackView.getChildAt(i - 1).getWidth());
resizeAnimation.setDuration(200);
stackView.getChildAt(i).startAnimation(resizeAnimation);
}
} else if (dy < 0) {
final int position = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (position == imageList.size() - 1) {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(1).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 1))
.into((ImageView) stackView.getChildAt(1));
} else if (position == imageList.size() - 2) {
stackView.removeView(secondStack);
stackView.addView(secondStack);
secondStack.getLayoutParams().height = firstStack.getHeight() - 20;
secondStack.getLayoutParams().width = firstStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(2).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 2))
.into((ImageView) stackView.getChildAt(2));
} else if (position == imageList.size() - 3) {
stackView.removeView(thirdStack);
stackView.addView(thirdStack);
thirdStack.getLayoutParams().height = secondStack.getHeight() - 20;
thirdStack.getLayoutParams().width = secondStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(3).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 3))
.into((ImageView) stackView.getChildAt(3));
} else {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
}
}
}
});
return view;
}
//In validateToken method data is taken from the json and set to adapter as follows.
private void validateToken() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (new ConnectionManager(getActivity()).isConnectedToInternet()) {
final SweetAlertDialog pDialog = new AlertDIalogMessage().showProgressDialog(getActivity(), "Loading...");
if (sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, "token_invalid").equals("token_invalid")) {
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
Log.e("Access Token", accessToken);
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
} else {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//this method is invoked when unauthorized response come from server
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
} else {
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet connection!")
.show();
}
}
No in onResume method i called validate token as follows:
#Override
public void onResume() {
super.onResume();
validateToken();
}
//Now when I call some activity from this fragment and come back with back pressed validate method is called and RecyclerView adapter is reloaded. Now what I want is to maintain the state of RecyclerView such that when I came back from activity RecyclerView stays in the scroll position from when activity is called. But problem for me is it always come from the start. I also see some Stack Overflow post and they suggest me to use Parceable but i don't get any benefit. Is is doing nothing.
Can try this.
You need to maintain an identifier for each row. Then save the first visible row's identifier before you go to the activity. Then when you come back you select that particular row again.

getView of element that you're swiping (onFling) for android?

I'm making a list with a linearLayout and adding TextViews depending on how many items I got in the database. Problem is that I want to be able to delete an item when I swipe left on the list. I was just wondering how to get the element (view) that you're swiping? Here's the code I got for adding a TextView.
for(int i = 0; i < nrOfTodos; i++) {
TextView v = new TextView(this);
String title = todos.get(i).getTitle();
System.out.println(title);
v.setText(title);
v.setHeight(listItemSize);
v.setAllCaps(true);
v.setTextColor(Color.parseColor("#FFD9A7"));
v.setTextSize(listItemSize/6);
v.setHorizontallyScrolling(false);
v.setMaxLines(1);
v.setEllipsize(TruncateAt.END);
v.setPadding(30, 50, 0, 0);
v.setId(i);
todoViews.add(v);
v.setOnTouchListener(new OnSwipeTouchListener(this) {
#Override
public void onSwipeLeft() {
/*
*
*
* TODO!!! NEXT PART OF MY PLAN TO WORLD DOMINATION!
*
*
*/
}
});
if(i%2 == 1) {
v.setBackgroundColor(Color.parseColor("#11FFFFFF"));
}
ll.addView(v, i);
}
and I also have this
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() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 50;
private static final int SWIPE_VELOCITY_THRESHOLD = 10;
#Override
public boolean onDown(MotionEvent e) {
//always return true since all gestures always begin with onDown and <br>
//if this returns false, the framework won't try to pick up onFling for example.
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();
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;
}
}
}
but I can't figure out how to actually get the view, get the titletext and remove that from the database (I can remove from the database, but I can't get what item was swiped ^^).
Any ideas would be greatly appreciated.
You may refer to this sample application Swipe_To_Delete
You may use ListView to list your data items which are got from the db.
Then modify the getSwipeItem() method in the MainActivity of the example, as follows.
#Override
public void getSwipeItem(boolean isRight, int position) {
[List_Of_Items].remove(position);
[Your_Adapter].notifyDataSetChanged();
}

Categories

Resources