• CardView之可切换式卡片


    今天我所要作的笔记是:

    可切换式的卡片CardView。

    Java代码部分

    1、我们要根据自己的当前版本号添加相对应的一个依赖:

    implementation 'com.android.support:cardview-v7:28.0.0'
    

    2、编写Fragment,在自己需要Activity中添加Fragment,在该Fragment编写如下代码。我的Fragment是DiscoveryFragment。

    public class DiscoveryFragment extends Fragment {
    
        private ViewPager mViewPager;
    
        private CardPagerAdapter mCardAdapter;
        private ShadowTransformer mCardShadowTransformer;
        private CardView mCardView;
        public DiscoveryFragment() {
            // Required empty public constructor
        }
    
        View view;
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            if(view == null) {
                view = inflater.inflate(R.layout.fragment_discovery, container, false);
                mCardView = view.findViewById(R.id.cardView);
                mCardView.setMaxCardElevation(mCardView.getCardElevation()
                        * CardAdapter.MAX_ELEVATION_FACTOR);
                initCard();
            }
            return view;
        }
    
        private void initCard() {
            mViewPager = view.findViewById(R.id.viewPager);
    
            mCardAdapter = new CardPagerAdapter();
            mCardAdapter.addCardItem(new CardItem(R.string.title_1, R.string.text_1));
            mCardAdapter.addCardItem(new CardItem(R.string.title_2, R.string.text_1));
            mCardAdapter.addCardItem(new CardItem(R.string.title_3, R.string.text_1));
            mCardAdapter.addCardItem(new CardItem(R.string.title_4, R.string.text_1));
    
            mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);
            mCardShadowTransformer.enableScaling(true);
    
            mViewPager.setAdapter(mCardAdapter);
            mViewPager.setPageTransformer(false, mCardShadowTransformer);
            mViewPager.setOffscreenPageLimit(3);
        }
        public CardView getCardView() {
            return mCardView;
        }
    }
    
    

    3、CardFragmentPagerAdapter

    public class CardFragmentPagerAdapter extends FragmentStatePagerAdapter implements CardAdapter {
    
        private List<DiscoveryFragment> mFragments;
        private float mBaseElevation;
    
        public CardFragmentPagerAdapter(FragmentManager fm, float baseElevation) {
            super(fm);
            mFragments = new ArrayList<>();
            mBaseElevation = baseElevation;
    
            for(int i = 0; i< 5; i++){
                addCardFragment(new DiscoveryFragment());
            }
        }
    
        @Override
        public float getBaseElevation() {
            return mBaseElevation;
        }
    
        @Override
        public CardView getCardViewAt(int position) {
            return mFragments.get(position).getCardView();
        }
    
        @Override
        public int getCount() {
            return mFragments.size();
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Object fragment = super.instantiateItem(container, position);
            mFragments.set(position, (DiscoveryFragment) fragment);
            return fragment;
        }
    
        public void addCardFragment(DiscoveryFragment fragment) {
            mFragments.add(fragment);
        }
    
    }
    

    4、CardPagerAdapter

    public class CardPagerAdapter extends PagerAdapter implements CardAdapter {
    
        private List<CardView> mViews;
        private List<CardItem> mData;
        private float mBaseElevation;
    
        public CardPagerAdapter() {
            mData = new ArrayList<>();
            mViews = new ArrayList<>();
        }
    
        public void addCardItem(CardItem item) {
            mViews.add(null);
            mData.add(item);
        }
    
        public float getBaseElevation() {
            return mBaseElevation;
        }
    
        @Override
        public CardView getCardViewAt(int position) {
            return mViews.get(position);
        }
    
        @Override
        public int getCount() {
            return mData.size();
        }
    
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(container.getContext())
                    .inflate(R.layout.adapter, container, false);
            container.addView(view);
            bind(mData.get(position), view);
            CardView cardView =  view.findViewById(R.id.cardView);
    
            if (mBaseElevation == 0) {
                mBaseElevation = cardView.getCardElevation();
            }
    
            cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
            mViews.set(position, cardView);
            return view;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            mViews.set(position, null);
        }
    
        private void bind(CardItem item, View view) {
            TextView titleTextView = (TextView) view.findViewById(R.id.titleTextView);
            TextView contentTextView = (TextView) view.findViewById(R.id.contentTextView);
            titleTextView.setText(item.getTitle());
            contentTextView.setText(item.getText());
        }
    
    }
    
    

    5、CardItem

    public class CardItem {
    
        private int mTextResource;
        private int mTitleResource;
    
        public CardItem(int title, int text) {
            mTitleResource = title;
            mTextResource = text;
        }
    
        public int getText() {
            return mTextResource;
        }
    
        public int getTitle() {
            return mTitleResource;
        }
    }
    

    6、ShadowTransformer

    public class ShadowTransformer implements ViewPager.OnPageChangeListener, ViewPager.PageTransformer {
    
        private ViewPager mViewPager;
        private CardAdapter mAdapter;
        private float mLastOffset;
        private boolean mScalingEnabled;
    
        public ShadowTransformer(ViewPager viewPager, CardAdapter adapter) {
            mViewPager = viewPager;
            viewPager.addOnPageChangeListener(this);
            mAdapter = adapter;
        }
    
        public void enableScaling(boolean enable) {
            if (mScalingEnabled && !enable) {
                // shrink main card
                CardView currentCard = mAdapter.getCardViewAt(mViewPager.getCurrentItem());
                if (currentCard != null) {
                    currentCard.animate().scaleY(1);
                    currentCard.animate().scaleX(1);
                }
            }else if(!mScalingEnabled && enable){
                // grow main card
                CardView currentCard = mAdapter.getCardViewAt(mViewPager.getCurrentItem());
                if (currentCard != null) {
                    currentCard.animate().scaleY(1.1f);
                    currentCard.animate().scaleX(1.1f);
                }
            }
    
            mScalingEnabled = enable;
        }
    
        @Override
        public void transformPage(View page, float position) {
    
        }
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int realCurrentPosition;
            int nextPosition;
            float baseElevation = mAdapter.getBaseElevation();
            float realOffset;
            boolean goingLeft = mLastOffset > positionOffset;
    
            // If we're going backwards, onPageScrolled receives the last position
            // instead of the current one
            if (goingLeft) {
                realCurrentPosition = position + 1;
                nextPosition = position;
                realOffset = 1 - positionOffset;
            } else {
                nextPosition = position + 1;
                realCurrentPosition = position;
                realOffset = positionOffset;
            }
    
            // Avoid crash on overscroll
            if (nextPosition > mAdapter.getCount() - 1
                    || realCurrentPosition > mAdapter.getCount() - 1) {
                return;
            }
    
            CardView currentCard = mAdapter.getCardViewAt(realCurrentPosition);
    
            // This might be null if a fragment is being used
            // and the views weren't created yet
            if (currentCard != null) {
                if (mScalingEnabled) {
                    currentCard.setScaleX((float) (1 + 0.1 * (1 - realOffset)));
                    currentCard.setScaleY((float) (1 + 0.1 * (1 - realOffset)));
                }
                currentCard.setCardElevation((baseElevation + baseElevation
                        * (CardAdapter.MAX_ELEVATION_FACTOR - 1) * (1 - realOffset)));
            }
    
            CardView nextCard = mAdapter.getCardViewAt(nextPosition);
    
            // We might be scrolling fast enough so that the next (or previous) card
            // was already destroyed or a fragment might not have been created yet
            if (nextCard != null) {
                if (mScalingEnabled) {
                    nextCard.setScaleX((float) (1 + 0.1 * (realOffset)));
                    nextCard.setScaleY((float) (1 + 0.1 * (realOffset)));
                }
                nextCard.setCardElevation((baseElevation + baseElevation
                        * (CardAdapter.MAX_ELEVATION_FACTOR - 1) * (realOffset)));
            }
    
            mLastOffset = positionOffset;
        }
    
        @Override
        public void onPageSelected(int position) {
    
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    }
    

    7、CardAdapter

    public interface CardAdapter {
    
        int MAX_ELEVATION_FACTOR = 8;
    
        float getBaseElevation();
    
        CardView getCardViewAt(int position);
    
        int getCount();
    }
    

    XML文件

    1、CardPagerAdapter的布局文件adapter

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:cardUseCompatPadding="true">
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="24dp">
    
                <TextView
                    android:id="@+id/titleTextView"
                    style="@style/TextAppearance.AppCompat.Title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
    
                <TextView
                    android:id="@+id/contentTextView"
                    style="@style/TextAppearance.AppCompat.Body1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"/>
    
                <Button
                    style="@style/ButtonStyle"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp40"
                    android:layout_marginTop="@dimen/dp100"
                    android:layout_gravity="bottom"
                    android:background="@color/green_theme"
                    android:text="开始悦读" />
            </LinearLayout>
    
        </FrameLayout>
    
    </android.support.v7.widget.CardView>
    
    

    2、fragment_discovery

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/greyf3"
        tools:context=".main_code.about_fragment.about_discovery.DiscoveryFragment">
        <android.support.v7.widget.CardView
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/cardView"
            app:cardUseCompatPadding="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center">
    
            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp400"
                android:layout_gravity="center"
                android:clipToPadding="false"
                android:overScrollMode="never"
                android:paddingLeft="@dimen/dp40"
                android:paddingRight="@dimen/dp40"
                android:paddingStart="@dimen/dp60" />
        </android.support.v7.widget.CardView>
    
    </LinearLayout>
    

    以上。
    代码来自:(致谢)
    https://blog.csdn.net/chenzheng8975/article/details/76976122

    The one who wants to wear the crown, bears the crown.
  • 相关阅读:
    VXDIAG VX Manager V1.8.0.0814更新指南
    Java Stream 源码分析
    RESTful接口实战
    Java面经
    开发中遇到的问题:push to origin/master was rejected错误解决方案
    开发遇到的问题:springboot问题:Unable to find main class
    java封神之路-stream流-进阶
    Java封神之路-stream流-入门
    Java封神之路-设计模式-工厂模式
    JAVA封神之路-设计模式-单例模式
  • 原文地址:https://www.cnblogs.com/catherineliu/p/13048302.html
Copyright © 2020-2023  润新知