java - How can I give an imageview click effect like a button on Android?

java - How can I give an imageview click effect like a button on Android?

Markos Agatha Author: Markos Agatha Date: 2022-08-17
java - How can I give an imageview click effect like a button on Android?

All you need to know about java - How can I give an imageview click effect like a button on Android? , in addintion to java - How can I make my ActionBar's "Up" button work like the phone's "Back" button? , java - How to rotate image in imageview on button click each time? , Java Android how can I make ImageView darker onClick , java - How can I make my Android SwipeableCardViews more like the IOS 7 mail app (swipe to show buttons)

  1. java - How can I give an imageview click effect like a button on Android?
  2. Question:

    I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clicked. How can I achieve that?


    Solution 1:

    You can do this with a single image using something like this:

         //get the image view
        ImageView imageView = (ImageView)findViewById(R.id.ImageView);
    
        //set the ontouch listener
        imageView.setOnTouchListener(new OnTouchListener() {
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        //overlay is black with transparency of 0x77 (119)
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        //clear the overlay
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
    
                return false;
            }
        });
    

    I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.

    Solution 2:

    You can design different images for clicked/not clicked states and set them in the onTouchListener as follows

    final ImageView v = (ImageView) findViewById(R.id.button0);
            v.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    switch (arg1.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        v.setImageBitmap(res.getDrawable(R.drawable.img_down));
                        break;
                    }
                    case MotionEvent.ACTION_CANCEL:{
                        v.setImageBitmap(res.getDrawable(R.drawable.img_up));
                        break;
                    }
                    }
                    return true;
                }
            });
    

    The better choice is that you define a selector as follows

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true"   
            android:drawable="@drawable/img_down" />
        <item android:state_selected="false"   
            android:drawable="@drawable/img_up" />
    </selector>
    

    and select the image in the event:

    v.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
                    return true;
                }
            });
    

    Solution 3:

    EDIT: Although the original answer below works and is easy to set up, refer to this post by an Android Developer Advocate at Google if you want / need a more efficient implementation. Also note that the android:foreground attribute is coming to all Views, including ImageView, by default in Android M.


    The problem with using a selector for an ImageView is that you can only set it as the view's background - as long as your image is opaque, you will not see the selector's effect behind it.

    The trick is to wrap your ImageView in a FrameLayout with the attribute android:foreground which allows us to define an overlay for its content. If we set android:foregroundto a selector (e.g.?android:attr/selectableItemBackground for API level 11+) and attach the OnClickListener to the FrameLayout instead of the ImageView, the image will be overlaid with our selector's drawable - the click effect we desire!

    Behold:

    <FrameLayout
        android:id="@+id/imageButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?android:attr/selectableItemBackground" >
    
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/yourImageFile" />
    
    </FrameLayout>
    

    (Note this should be placed within your parent layout.)

    final View imageButton = findViewById(R.id.imageButton);
    imageButton.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            // do whatever we wish!
        }
    });
    

  3. java - How can I make my ActionBar's "Up" button work like the phone's "Back" button?
  4. Question:

    I have a ViewPager with Fragments. When a button is clicked in the Fragment, I launch an Activity on mine. Pressing the back button on my phone when I'm in the Activity, takes me back to my previous screen i.e. the one with the Fragments in the ViewPager.

    I'd like to enable the "up" button in my ActionBar and in order to do so, I've written the following code:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
    
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    

    Now the "up" button is shown, but clicking it doesn't take me back to the previous screen. I'd like the "up" button to the same thing as the "back" button.

    How can I do this? What am I doing wrong?

    Thanks.


    Solution 1:

    You need also to implement what should be done when the up button is clicked:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { 
            switch (item.getItemId()) {
            case android.R.id.home: 
                onBackPressed();
                return true;
            }
    
        return super.onOptionsItemSelected(item);
    }
    

  5. java - How to rotate image in imageview on button click each time?
  6. Question:

    This is java code.I am getting image from image gallery.I have one Button and one ImageView. It is rotating only one time.When I again click button it is not rotating image.

    public class EditActivity extends ActionBarActivity
    {
    private Button rotate;
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        rotate=(Button)findViewById(R.id.btn_rotate1);
        imageView = (ImageView) findViewById(R.id.selectedImage);
        String path = getIntent().getExtras().getString("path");
        final Bitmap bitmap = BitmapFactory.decodeFile(path);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 510, 500,
                false));
        rotate.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
              {                  
                imageView.setRotation(90);
    
    
            }
        });
    
    
    
    }
    


    Solution 1:

    Change your onClick() method to

    @Override
    public void onClick(View v)
    {                  
        imageView.setRotation(imageView.getRotation() + 90);
    }
    

    Notice, what the docs say

    Sets the degrees that the view is rotated around the pivot point. Increasing values result in clockwise rotation.


    I'd like to update my answer to show how to use RotateAnimation to achieve the same effect in case you're also targeting Android devices running Gingerbread (v10) or below.

    private int mCurrRotation = 0; // takes the place of getRotation()
    

    Introduce an instance field to track the rotation degrees as above and use it as:

    mCurrRotation %= 360;
    float fromRotation = mCurrRotation;
    float toRotation = mCurrRotation += 90;
    
    final RotateAnimation rotateAnim = new RotateAnimation(
            fromRotation, toRotation, imageview.getWidth()/2, imageView.getHeight()/2);
    
    rotateAnim.setDuration(1000); // Use 0 ms to rotate instantly 
    rotateAnim.setFillAfter(true); // Must be true or the animation will reset
    
    imageView.startAnimation(rotateAnim);
    

    Usually one can setup such View animations through XML as well. But, since you have to specify absolute degree values in there, successive rotations will repeat themselves instead of building upon the previous one to complete a full circle. Hence, I chose to show how to do it in code above.

  7. Java Android how can I make ImageView darker onClick
  8. Question:

    As an iOS developer told me, iOS make an image darker when somebody tap it (I don't know how true it is) so I need the same thing.

    as I understand, I need a usual selector.xml to make a drawable with different states. What I need is to darken the image in a simple way, may be in xml-drawable somehow so I don't have to use Photoshop in which I have no skill.

    Is there a way to do so on xml-level?


    Solution 1:

    You could use the following code in your java class:

    mView.getBackground().setColorFilter(Color.parseColor(<Color code of your choice>), PorterDuff.Mode.DARKEN);
    

    This line above changes the color of the view to to a share of color you suggest in Color.parseColor() and a shade like how you define it using PorterDuff.Mode. Call the above code on click of a button to check if the color change is taking effect.

    Solution 2:

    You May Put a dark rectangle behind your bitmap and set the Bitmap's Opacity instead of trying in xml.

    Solution 3:

    I used

    private void darkenImage(ImageView imageView)
    {
        imageView.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
    }
    
    private void undarkenImage(ImageView imageView)
    {
        imageView.clearColorFilter();
    }
    
    private boolean isImageDarkened(ImageView image)
    {
        return image.getColorFilter() != null;
    }
    

    works really well !

  9. java - How can I make my Android SwipeableCardViews more like the IOS 7 mail app (swipe to show buttons)
  10. Question:

    How can I make my SwipeableCardViews more like the IOS 7 mail app (swipe to show buttons)

    So far I have created an android application which allows the user to swipe Cardviews either to the left or to the right. Each card has 2 buttons, which at a later date I will assign functions to.

    (As the image below shows):

    enter image description here

    What I would like to accomplish is (but don't yet know how), is instead of swiping to the left or right to completely remove a card.

    Instead I would like either swipe gesture, to reveal a button which was hidden underneath the right or left card.

    The IOS 7 mail app already performs this function (screenshot below) I would like to perform this in Android using Cardviews (not ListViews).

    How can I go about doing this?

    enter image description here

    My code so far:

    MainActivity.java

    public class MainActivity extends ActionBarActivity {
        private RecyclerView mRecyclerView;
        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 %2d", 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);
    
            mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mRecyclerView.setAdapter(mAdapter);
    
            SwipeableRecyclerViewTouchListener swipeTouchListener =
                    new SwipeableRecyclerViewTouchListener(mRecyclerView,
                            new SwipeableRecyclerViewTouchListener.SwipeListener() {
                                @Override
                                public boolean canSwipe(int position) {
                                    return true;
                                }
    
                                @Override
                                public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
                                    for (int position : reverseSortedPositions) {
                                        mItems.remove(position);
                                        mAdapter.notifyItemRemoved(position);
                                    }
                                    mAdapter.notifyDataSetChanged();
                                }
    
                                @Override
                                public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
                                    for (int position : reverseSortedPositions) {
                                        mItems.remove(position);
                                        mAdapter.notifyItemRemoved(position);
                                    }
                                    mAdapter.notifyDataSetChanged();
                                }
                            });
    
            mRecyclerView.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.java

    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 mDownX;
        private float mDownY;
        private boolean mSwiping;
        private int mSwipingSlop;
        private VelocityTracker mVelocityTracker;
        private int mDownPosition;
        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) {
                        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(1)
                                .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 != ListView.INVALID_POSITION) {
                        // dismiss
                        final View downView = mDownView; // mDownView gets null'd before animation ends
                        final int downPosition = mDownPosition;
                        ++mDismissAnimationRefCount;
                        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(1)
                                .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(1f,
                                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 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(1f);
                            pendingDismiss.view.setTranslationX(0);
                            lp = pendingDismiss.view.getLayoutParams();
                            lp.height = originalHeight;
                            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();
                    }
                }
            });
    
            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;
            }
        }
    }
    

    activity_main.xml

    <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
    
    </android.support.v7.widget.RecyclerView>
    

    card_view_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        android:orientation="vertical"
        card_view:cardCornerRadius="5dp">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <TextView
                android:id="@+id/card_view_title"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:textColor="@android:color/black"
                android:textSize="24sp" />
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/card_view_title"
                android:layout_centerHorizontal="true"
                android:gravity="center">
    
                <Button
                    android:id="@+id/card_view_button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Button1" />
    
                <Button
                    android:id="@+id/card_view_button2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Button2" />
            </LinearLayout>
        </RelativeLayout>
    
    </android.support.v7.widget.CardView>
    


    Solution 1:

    Just for a reference you can use these swipe layout library . its includes swiping actions which you were searching . Hope it ill be helpful

    enter image description here

    Solution 2:

    I've just done this. This is how it looks like:

    enter image description here

    I don't have any CardView but you can have any layout (so you can add the support lib CardView or whatever you like).

    This is how I did it. I used this library. Since the library has minSdkVersion 15 and we have 14, I copy-pasted the following classes directly from GitHub: OnItemClickListener, RecyclerViewAdapter, SwipeableItemClickListener, SwipeToDismissTouchListener and ViewAdapter (this are the only ones you need if you use a RecyclerView).

    Because the lib has not been updated yet, you'll need to add the following method into SwipeableItemClickListener:

    @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    }
    

    Your list item layout should have the following structure:

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="@dimen/list_item_article_height"
        >
    
        <!-- This is the layout you see always -->    
        <include
            layout="@layout/list_item_article"
            tools:visibility="gone"
            />
    
        <!-- This is the layout shown after swiping. Must have visibility="gone" -->
        <LinearLayout
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            >    
            <TextView
                android:id="@+id/swipe_cancel"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:text="@string/swipe_cancel"
                android:gravity="center"
                />    
            <TextView
                android:id="@+id/swipe_delete"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="@string/swipe_delete"
                android:gravity="center"
                android:background="#f00"
                android:textColor="#fff"
                />    
        </LinearLayout>    
    </FrameLayout>
    

    Then simply add this code to your Activity/Fragment after creating the RecyclerView and setting it's adapter:

    final SwipeToDismissTouchListener<RecyclerViewAdapter> touchListener =
            new SwipeToDismissTouchListener<>(
                    new RecyclerViewAdapter(mRecyclerView),
                    new SwipeToDismissTouchListener.DismissCallbacks<RecyclerViewAdapter>() {
                        @Override
                        public boolean canDismiss(int position) {
                            return true;
                        }
                        @Override
                        public void onDismiss(RecyclerViewAdapter recyclerView, int position) {
                            // remove item at position and notify adapter
                        }
                    }
            );
    mRecyclerView.setOnTouchListener(touchListener);
    mRecyclerView.addOnScrollListener((RecyclerView.OnScrollListener) touchListener.makeScrollListener());
    mRecyclerView.addOnItemTouchListener(new SwipeableItemClickListener(
            getActivity(),
            new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (view.getId() == R.id.swipe_delete) {
                        touchListener.processPendingDismisses();
                    } else {
                        touchListener.undoPendingDismiss();
                    }
                }
            }
    ));
    

    Solution 3:

    If you want to have only add and delete button you can use RecyclerView but with RecyclerView.Adapter not CardViewAdapter. Here is an example:

    public class MyActivity extends Activity {
        private RecyclerView mRecyclerView;
        private RecyclerView.Adapter mAdapter;
        private RecyclerView.LayoutManager mLayoutManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.my_activity);
            mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    
            // use this setting to improve performance if you know that changes
            // in content do not change the layout size of the RecyclerView
            mRecyclerView.setHasFixedSize(true);
    
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(mLayoutManager);
    
            // specify an adapter (see also next example)
            mAdapter = new MyAdapter(myDataset);
            mRecyclerView.setAdapter(mAdapter);
        }
        ...
    }
    
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
        private String[] mDataset;
    
        // Provide a reference to the views for each data item
        // Complex data items may need more than one view per item, and
        // you provide access to all the views for a data item in a view holder
        public static class ViewHolder extends RecyclerView.ViewHolder {
            // each data item is just a string in this case
            public TextView mTextView;
            public ViewHolder(TextView v) {
                super(v);
                mTextView = v;
            }
        }
    
        // Provide a suitable constructor (depends on the kind of dataset)
        public MyAdapter(String[] myDataset) {
            mDataset = myDataset;
        }
    
        // Create new views (invoked by the layout manager)
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            // create a new view
            View v = LayoutInflater.from(parent.getContext())
                                   .inflate(R.layout.my_text_view, parent, false);
            // set the view's size, margins, paddings and layout parameters
            ...
            ViewHolder vh = new ViewHolder(v);
            return vh;
        }
    
        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            holder.mTextView.setText(mDataset[position]);
    
        }
    
        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return mDataset.length;
        }
    }