本文实例为大家分享了ViewPager RadioGroup实现左右滑动卡片布局的具体代码,供大家参考,具体内容如下

效果如图所示:

1.选择某个界面时,对应的第几个小圆点亮:

通过selector制造圆点和进行更改小圆点被选择和未被选择时的颜色:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape>
            <solid android:color="@color/app_green_area" />
            <corners android:radius="5dp" />

        </shape>
    </item>
    <item android:state_checked="false">
        <shape>
            <solid android:color="#fff" />
            <corners android:radius="5dp" />
            <stroke android:width="0.2dp"
                android:color="@color/app_line"/>
        </shape>
    </item>
</selector>

2.主界面布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:background="@color/app_gray_bg">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:textColor="@color/colorPrimary"
            android:text="health页面"/>
        <android.support.v4.view.ViewPager
            android:id="@ id/view_pager"
            android:layout_gravity="center"
            android:overScrollMode="never"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <RadioGroup
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:id="@ id/group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal">

        <RadioButton
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/selector_point"
            android:button="@null" />

        <RadioButton
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/selector_point"
            android:button="@null" />

        <RadioButton
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/selector_point"
            android:button="@null" />

    </RadioGroup>
</RelativeLayout>

3.主界面内嵌的卡片视图布局:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="2dp"
    app:cardCornerRadius="8dp">
    <LinearLayout
        android:id="@ id/chart_bar"
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@ id/tv_title"
            android:textColor="@color/app_black"
            android:gravity="center"
            android:textSize="30sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <LinearLayout
            android:adjustViewBounds="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout
                android:id="@ id/layout_data1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:visibility="visible"
                android:orientation="vertical">
                <TextView
                    android:text="layout_data1"
                    android:textSize="30sp"
                    android:textColor="@color/colorPrimary"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
            <LinearLayout
                android:id="@ id/layout_data2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:visibility="visible"
                android:orientation="vertical">
                <TextView
                    android:text="layout_data2"
                    android:textSize="30sp"
                    android:textColor="@color/colorPrimary"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
            <LinearLayout
                android:id="@ id/layout_data3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:visibility="visible"
                android:orientation="vertical">
                <TextView
                    android:text="layout_data3"
                    android:textSize="30sp"
                    android:textColor="@color/colorPrimary"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

4.定义卡片之间切换的样式:

/**
 * 卡片之间切换的样式
 */

public class ZoomOutPageTransformer implements ViewPager.PageTransformer {

    public static final float MAX_SCALE = 0.9f;
    public static final float MIN_SCALE = 0.8f;

    @Override
    public void transformPage(View page, float position) {

        position = position < -1 ? -1 : position;
        position = position > 1 ? 1 : position;

        float tempScale = position < 0 ? 1   position : 1 - position;

        float slope = (MAX_SCALE - MIN_SCALE) / 1;
        float scaleValue = MIN_SCALE   tempScale * slope;
        page.setScaleX(scaleValue);
        page.setScaleY(scaleValue);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            page.getParent().requestLayout();
        }
    }
}

5.定义用于加载卡片视图的layout控件,方便自定义宽高比例:

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * 用于加载卡片视图
 */

public class RatioLayout extends ViewGroup {

    private float heightWidthRatio = 0.325f;

    public RatioLayout(Context context) {
        this(context, null);
    }

    public RatioLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.RatioLayout);
        heightWidthRatio = getFloatFromString(a.getString(R.styleable.RatioLayout_height_width_ratio));
        a.recycle();
    }

    public void setHeightWidthRatio(String ratio) {
        heightWidthRatio = getFloatFromString(ratio);
    }

    public static float getFloatFromString(String src) {
        if (TextUtils.isEmpty(src)) {
            return 0;
        }
        float result;
        try {
            result = Float.parseFloat(src);
            return result;
        } catch (Exception e) {
        }

        String[] strs = src.split("/");
        if (strs.length == 2) {
            try {
                float molecular = Float.parseFloat(strs[0]);//分子
                float denominator = Float.parseFloat(strs[1]);//分子
                result = molecular / denominator;
            } catch (Exception e) {
                result = 0;
            }
        } else {
            result = 0;
        }
        return result;
    }

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom);
    }

    void layoutChildren(int left, int top, int right, int bottom) {
        final int count = getChildCount();
        for (int i = 0; i < count; i  ) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = child.getLayoutParams();
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();
                child.layout(0, 0, width, 0   height);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (heightWidthRatio > 0) {
            int width = getMeasuredWidth();
            int height = (int) (width * heightWidthRatio);
            setMeasuredDimension(width, height);
            int count = getChildCount();
            if (count >= 1) {
                for (int i = 0; i < count; i  ) {
                    View child = getChildAt(i);
                    child.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
                }
            }
        }
    }
}

6.卡片布局对应的activity:

public class FrHealthChart extends Fragment {

    public static final String DATA = "_data";
    @BindView(R.id.layout_data1)
    LinearLayout layoutData1;
    @BindView(R.id.layout_data2)
    LinearLayout layoutData2;
    @BindView(R.id.layout_data3)
    LinearLayout layoutData3;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.chart_bar)
    LinearLayout chartBar;

    private int position;//用于标识选择的是哪个layout

    public static Fragment getInstance(int position) {
        FrHealthChart frHealthChart = new FrHealthChart();
        Bundle bundle = new Bundle();
        bundle.putInt(DATA, position);
        frHealthChart.setArguments(bundle);
        return frHealthChart;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.from(getContext()).inflate(R.layout.fragment_health_chart, container, false);
        ButterKnife.bind(this, view);
        Bundle bundle = getArguments();
        if (bundle != null) {
            position = bundle.getInt(DATA);
            initCard();
        }
        //加载卡片视图,控制宽高比例
        RatioLayout ratioLayout = new RatioLayout(getContext());
        ratioLayout.addView(view);
        ratioLayout.setHeightWidthRatio("67/52");
        return ratioLayout;
    }

    private void initCard() {
        switch (position) {
            case 0://显示layoutData1
                layoutData1.setVisibility(View.VISIBLE);
                layoutData2.setVisibility(View.GONE);
                layoutData3.setVisibility(View.GONE);
                initData();
                break;
            case 1://显示layoutData2
                layoutData1.setVisibility(View.GONE);
                layoutData2.setVisibility(View.VISIBLE);
                layoutData3.setVisibility(View.GONE);
                initData();
                break;
            case 2://显示layoutData3
                layoutData1.setVisibility(View.GONE);
                layoutData2.setVisibility(View.GONE);
                layoutData3.setVisibility(View.VISIBLE);
                initData();
                break;
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        switch (position) {
            case 0:
                tvTitle.setText("卡片内容"   "layout_data1");
                chartBar.setBackgroundColor(Color.parseColor("#6ddac6"));
                break;
            case 1:
                tvTitle.setText("卡片内容"   "layout_data2");
                chartBar.setBackgroundColor(getResources().getColor(R.color.app_green_area));
                break;
            case 2:
                tvTitle.setText("卡片内容"   "layout_data3");
                chartBar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                break;
        }
    }

}

7.主界面的activity代码:

public class FrHealth extends Fragment implements ViewPager.OnPageChangeListener {

    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.group)
    RadioGroup group;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_health, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        RadioButton childAt = (RadioButton) group.getChildAt(0);
        childAt.setChecked(true);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());//设置卡片之间切换的样式
        viewPager.setOffscreenPageLimit(3);//限定预加载的卡片个数
        ViewGroup.LayoutParams layoutParams = viewPager.getLayoutParams();
//        layoutParams.height = AppUtil.dp2px(getContext(), 400);
        float scale = getContext().getResources().getDisplayMetrics().density;
        layoutParams.height = (int) (400 * scale   0.5F);//计算高宽
        layoutParams.width = (int) (layoutParams.height * 0.8);
        if (viewPager.getParent() instanceof ViewGroup) {
            ViewGroup viewParent = ((ViewGroup) viewPager.getParent());
            viewParent.setClipChildren(false);
            viewPager.setClipChildren(false);
        }
        viewPager.addOnPageChangeListener(this);
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(myPagerAdapter);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //根据监听viewPager的PageChangeListener获得选择的是哪个卡片,并把其对应位序的小圆点设置为选定状态
        RadioButton childAt = (RadioButton) group.getChildAt(position);
        childAt.setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    class MyPagerAdapter extends FragmentPagerAdapter {
        HashMap<Integer, Fragment> map = new HashMap<>();

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            FrHealthChart fragment = (FrHealthChart) map.get(position);
            if (fragment == null) {
                fragment = (FrHealthChart) FrHealthChart.getInstance(position);
                map.put(position, fragment);
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 3;//卡片个数
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

ViewPager+RadioGroup实现左右滑动卡片布局的更多相关文章

  1. android – 在listview中添加viewpager作为滚动标题

    我试图在列表标题中添加Viewpager(使用支持库4),但它没有显示任何内容.这是我的代码请帮忙.它将在列表标题中不作为项目,因此它不应该是一个问题.解决方法listadapter之后的listview页眉和页脚显示.如果你尝试setadapter,并且看不到viewpager.检查viewpager的宽度和高度.如果viewpager的宽度或高度值为0.在viewgroup中创建LienarL

  2. 从ViewPager Fragments中隐藏Android应用程序中的软键盘

    我有一个Android应用程序,其中包含一个包含2个片段的ViewPager.第一个片段包含EditText字段.当应用程序启动时,该字段立即获得焦点并启动软键盘.第二个片段仅包含一个列表.当我从片段1滑动到片段2时,我希望键盘能够消失.我尝试过的任何东西似乎都没有用.键盘不仅保持在视图中,还继续更新片段1的EditText字段.我想我要么使用不正确的代码来隐藏键盘或将其放在错误的位置.如果任何人都可以发布正确实现的示例,将不胜感激!

  3. android – Slider Menu片段中的可交换选项卡

    我已经通过引用thistutorial实现了导航抽屉,现在我想要做的是在片段内显示滑动标签.即当我点击导航抽屉中的一个项目时,让我们说第一个项目,它应显示该项目的滑动标签.如果item1是Events,当我点击它时,它应该显示滑动标签.但我面临以下问题:–>如何在片段内实现视图寻呼机?

  4. android – 如何在ViewPager中使用cursorLoader?

    解决方法我无法评论,所以我正在写一个答案..您有一个实现LoaderCallbacks的活动.加载数据时,您的活动会收到onLoadFinished回调.在此方法中,您有一个应该在ViewPager中显示的Cursor.要显示Cursor中的数据,请在适配器上调用swapCursor方法.因此,每次加载数据时都不要创建适配器.创建一次,然后只需调用swapCursor即可.此外,每次都找不到ViewPager–findViewById是一个繁重的操作,它应该在创建视图层次结构后执行.所以,你的onLoad

  5. android – FragmentPagerAdapter不会在方向更改时重新创建片段吗?

    可能是其他一些解决方案?这些碎片有什么问题?

  6. android – Horizo​​ntalScrollView还是Carrousel?

    我在SO上找到的最接近的例子是here.这正是我需要的,但我已经测试了给出的答案,但它对我不起作用……但问题中的图像正是我想要的.任何人都可以指导我这样做吗?编辑2:根据你给出的两个例子,你看过this和this吗?这就是你要找的东西吗?

  7. 选项卡图标和文本均使用android设计支持库

    解决方法你是什么意思未被选中.你能分享一下你想要达到的目标以及你现在所处的位置.我不推荐你的做法.它做了很多不需要的东西来解决你的问题.我建议使用TabLayout类中的图标和文本,只需设置图标和文本.或者,如果需要,甚至是自定义布局,但使用TabLayout中的text1和图标.这样做有什么问题吗?

  8. Android在FragmentPagerAdapter中的Fragment中设置TextView文本

    更新:那么做这样的事情?

  9. android – 为什么ViewPager中的第一个视图显示为空?

    我有一个使用以下适配器的viewpager,在加载后,第一个视图显示为空,但事实并非如此.如果我滚动到下一个视图,然后向后滚动,我可以看到内容.以下是从我的活动中实现它的代码……解决方法尝试添加followindonCreate方法,我的代码工作.也许只是因为在不合适的时间调用resetPages()?

  10. Android ViewPager CrossFade动画

    我为android实现了BottomNavigation视图,我有一些片段显示为BottomNavigation页面.根据GoogleMaterialDesignGuideLines我想用交叉淡入淡出动画显示片段.通过触摸BottomNavigation的项目,我的ViewpPager使用默认幻灯片动画更改片段.我在this和this阅读了一些解决方案.但这些并不是真正的淡入淡出动画,我无法设置渐

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部