RecycleView&&Framgment的使用

不问归期 提交于 2020-01-19 04:34:01

一..添加依赖

dependencies {
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation  'com.android.support:recyclerview-v7:28.0.0'
}

二.布局文件

1.layout/activity_main..xml

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

    <!--<FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>-->
    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <RadioGroup
        android:id="@+id/main_tab_menu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/main_tab_home"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="2dp"
            android:layout_weight="1"
            android:button="@null"
            android:checked="true"
            android:drawableTop="@drawable/tab_home_bg"
            android:gravity="center"
            android:paddingTop="8dp"
            android:text="@string/home"
            android:textColor="@color/tab_click_color"
            android:textSize="12sp" />

        <RadioButton
            android:id="@+id/main_tab_cart"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="2dp"
            android:layout_weight="1"
            android:button="@null"
            android:checked="false"
            android:drawableTop="@drawable/tab_cart_background"
            android:gravity="center"
            android:paddingTop="8dp"
            android:text="@string/cart"
            android:textColor="@color/tab_click_color"
            android:textSize="12sp" />
    </RadioGroup>

</LinearLayout>

2.layout/home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <SearchView
        android:id="@+id/home_sv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="60dp"
        android:layout_marginTop="20dp"
        android:iconifiedByDefault="false"
        android:queryHint="@string/home_sv_text"
        android:inputType="textFilter"/>
    <RadioGroup
        android:id="@+id/home_btngroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="30dp"
        android:layout_marginRight="30dp">
        <RadioButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:layout_gravity="bottom"
            android:layout_marginBottom="2dp"
            android:paddingTop="2dp"
            android:drawableTop="@drawable/ic_home_click"
            android:text="@string/home_btn_hot"
            android:gravity="center"
            android:textSize="12sp"/>
        <RadioButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:layout_gravity="bottom"
            android:layout_marginBottom="2dp"
            android:paddingTop="2dp"
            android:drawableTop="@drawable/ic_home_click"
            android:text="@string/home_btn_hot"
            android:gravity="center"
            android:textSize="12sp"/>
    </RadioGroup>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hot"
        android:textSize="16sp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="#ff0000"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/home_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>
</LinearLayout>

 

3.layout/item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:text="@string/text"
        android:textColor="#ff0000"
        android:textSize="18sp"/>

    </RelativeLayout>

 

三、UI美化

1.drawable/tab_home_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_home_click" android:state_checked="true"/>
    <item android:drawable="@drawable/ic_home" android:state_checked="false"/>
</selector>

2.color/tab_click_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#ec7c1d"/>
    <item android:state_checked="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/darker_gray"/>

</selector>

四.Java文件

1.MainActivity.java

package com.example.myfragment;

import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int HOME = 1;
    private static final int CART = 2;
    private int curent_tab = -1;

    private HomeFragment homeFragment;
    private CartFragment cartFragment;
    private RadioGroup tab;
    private RecyclerView home_rv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTab();
    }

    private void initTab() {
        curent_tab = HOME;
        if (homeFragment==null)
            homeFragment = new HomeFragment();

        tab = findViewById(R.id.main_tab_menu);
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content,homeFragment).commit();



        tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId){
                    case R.id.main_tab_home:
                        if (null == homeFragment){
                            homeFragment = new HomeFragment();
                        }
                    break;

                    case R.id.main_tab_cart:
                        if (null == cartFragment){
                            cartFragment = new CartFragment();
                        }
                    break;
                }
            }
        });
    }
}

 

2.HomeFragment.java

package com.example.myfragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private RecyclerView home_rv;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.home,container,false);
        home_rv = view.findViewById(R.id.home_rv);
        List<String> data=new ArrayList<>();
        for (int i=0;i<30;i++){
            data.add("Item"+i);
        }

        home_rv.setLayoutManager(new LinearLayoutManager(getContext()));
        home_rv.addItemDecoration(new RecycleViewDivider(getContext(),RecyclerView.HORIZONTAL));
        home_rv.setAdapter(new rv_adapter(getContext(),data));
        return view;
    }
}

3.rv_adapter.java

package com.example.myfragment;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class rv_adapter extends RecyclerView.Adapter<rv_adapter.MyViewHolder> {
    private Context context;
    private List<String> data;

    public rv_adapter(Context context,List<String> data) {
        this.data = data;
        this.context = context;
    }

    //创建ViewHolder对象
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        //实例化Item布局的View对象
       View v =View.inflate(context,R.layout.item,null);
       //返回MyViewholder对象
        return new MyViewHolder(v);
    }
    //绑定数据
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {
        viewHolder.tv_item.setText(data.get(i));
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_item;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_item = itemView.findViewById(R.id.tv_content);

        }
    }
}

4.RecycleViewDivider.java

package com.example.myfragment;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class RecycleViewDivider extends RecyclerView.ItemDecoration {

    private Paint mPaint;
    private Drawable mDivider;
    private int mDividerHeight = 2;//分割线高度,默认为1px
    private int mOrientation;//列表的方向:LinearLayoutManager.VERTICAL或LinearLayoutManager.HORIZONTAL
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    /**
     * 默认分割线:高度为2px,颜色为灰色
     *
     * @param context
     * @param orientation 列表方向
     */
    public RecycleViewDivider(Context context, int orientation) {
        if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL) {
            throw new IllegalArgumentException("请输入正确的参数!");
        }
        mOrientation = orientation;
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation 列表方向
     * @param drawableId  分割线图片
     */
    public RecycleViewDivider(Context context, int orientation, int drawableId) {
        this(context, orientation);
        mDivider = ContextCompat.getDrawable(context, drawableId);
        mDividerHeight = mDivider.getIntrinsicHeight();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation   列表方向
     * @param dividerHeight 分割线高度
     * @param dividerColor  分割线颜色
     */
    public RecycleViewDivider(Context context, int orientation, int dividerHeight, int dividerColor) {
        this(context, orientation);
        mDividerHeight = dividerHeight;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(dividerColor);
        mPaint.setStyle(Paint.Style.FILL);
    }


    //获取分割线尺寸
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(0, 0, 0, mDividerHeight);
    }

    //绘制分割线
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if (mOrientation == LinearLayoutManager.VERTICAL) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    //绘制横向 item 分割线
    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + layoutParams.bottomMargin;
            final int bottom = top + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }

    //绘制纵向 item 分割线
    private void drawVertical(Canvas canvas, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + layoutParams.rightMargin;
            final int right = left + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!