《第一行代码》笔记(23)——CardView的简单使用

package com.zjw.mymaterialdesign5;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

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

import butterknife.BindView;
import butterknife.ButterKnife;

//12.5 p430 卡片式布局
//这一章从ToolBar开始应该都是连着的,只是我把它们都拆开来了,其余可参看前面笔记
//12.5.1 p431 CardView
/*
CardView其实也是一个FrameLayout,只是额外提供了圆角和阴影等效果

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    app:elevation="5dp">

         <TextView
              android:id="@+id/info_text"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>

</android.support.v7.widget.CardView>
其中 app:cardCornerRadius="4dp"属性指定卡片圆角的弧度,数值越大,弧度越大
    app:elevation="5dp"属性指定卡片的高度,数值越大,高度越大,投影范围越大,投影效果越淡
 */
/*
1.依赖:
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    glide:图片加载库,可加载本地图片、网络图片、GIF图片,甚至本地视频
    glide项目地址:https://github.com/bumptech/glide

2.Fruit实体:(String name;int imageId;)

3.recyclerView子项布局
<?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="wrap_content"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/fruit_image"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:scaleType="centerInside"
            android:src="@drawable/apple_pic"/>
        <TextView
            android:id="@+id/fruit_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:text="尚未加载"
            android:textSize="16sp"/>
    </LinearLayout>
</android.support.v7.widget.CardView>

4.改主布局
scaleType属性:
center  按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分显示
centerCrop  按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长(宽)
centerInside  将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片长/宽等于或小于View的长/宽
fitCenter  把图片按比例扩大/缩小到View的宽度,居中显示
fitEnd   把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置
fitStart  把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置
fitXY  把图片 不按比例扩大/缩小到View的大小显示
matrix 用矩阵来绘制,动态缩小放大图片来显示

5.recyclerView适配器
package com.zjw.mymaterialdesign5;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private Context mContext;
    private final List<Fruit> mFruitList;

    static class ViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View itemView) {
            super(itemView);
            cardView = (CardView) itemView;
            fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
            fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
        }
    }

    public FruitAdapter(List<Fruit> fruitList) {
        this.mFruitList = fruitList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mContext == null) {
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.fruit_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        //holder.fruitImage.setImageResource(fruit.getImageId());
        Glide.with(mContext).load(fruit.getImageId()).into(holder.fruitImage);
        holder.fruitName.setText(fruit.getName());
    }

    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

6.改主代码
 */
//此时RecyclerView会遮挡Toolbar

//12.5.2 p437 AppBarLayout
/*
遮挡原因:
CoordinateLayout是加强版FrameLayout,Toolbar与RecyclerView都在里面
不明确定位,默认在左上角,产生遮挡
解决方法一:向下偏移一个Toolbar高度
解决办法二:使用AppBarLayout
 */
/*
AppBarLayout:Design Support库
AppBarLayout实际上是一个垂直方向的LinearLayout,内部做了滚动事件封装,应用了Material Design设计理念
使用:
1.将Toolbar放入AppBarLayout
2.给RecyclerView指定一个布局行为
 */
/*
修改主布局代码:
有变动部分:
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/tb"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
        </android.support.v7.widget.RecyclerView>
其中app:layout_behavior="@string/appbar_scrolling_view_behavior"字符串由Design Support库提供,指定一个行为
 */
/*
关于行为behavior
可参考博客:http://www.cnblogs.com/android-blogs/p/5867398.html
 */
/*
当RecyclerView 滚动时通知了AppBarLayout
AppBarLayout内部子控件可以可以指定如何去影响这些事件
通过:app:layout_scrollFlags属性
改动主布局代码:
<android.support.v7.widget.Toolbar
                android:id="@+id/tb"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_scrollFlags="scroll|enterAlways|snap">
            </android.support.v7.widget.Toolbar>
其中app:layout_scrollFlags="scroll|enterAlways|snap",
scroll表示当RecyclerView向上滚动时,Toolbar会跟着一起向上滚动并实现隐藏
enterAlways表示当RecyclerView向下滚动时,Toolbar会跟着一起向下滚动并重新显示
snap表示当Toolbar还没有完全隐藏或显示的时候,会根据当前滚动的距离,自动选择是隐藏还是显示
 */

public class UseOfCardView extends AppCompatActivity {

    @BindView(R.id.tb)
    Toolbar mTb;
    @BindView(R.id.navigation)
    NavigationView mNavigation;
    @BindView(R.id.dl)
    DrawerLayout mDl;
    @BindView(R.id.acb)
    FloatingActionButton mAcb;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    //准备数据
    private String[] arr = {"apple", "banana", "orange", "watermelon",
            "pear", "grape", "pineapple", "strawberry", "cherry"
            , "mango", "apple", "banana", "orange", "watermelon",
            "pear", "grape", "pineapple", "strawberry", "cherry"
            , "mango"};
    private int[] arrId = {R.drawable.apple_pic, R.drawable.banana_pic, R.drawable.orange_pic, R.drawable.watermelon_pic,
            R.drawable.pear_pic, R.drawable.grape_pic, R.drawable.pineapple_pic, R.drawable.strawberry_pic, R.drawable.cherry_pic,
            R.drawable.mangp_pic, R.drawable.apple_pic, R.drawable.banana_pic, R.drawable.orange_pic, R.drawable.watermelon_pic,
            R.drawable.pear_pic, R.drawable.grape_pic, R.drawable.pineapple_pic, R.drawable.strawberry_pic, R.drawable.cherry_pic,
            R.drawable.mangp_pic};
    private List<Fruit> fruitList = new ArrayList<Fruit>();
    private FruitAdapter mFruitAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_use_of_card_view);
        ButterKnife.bind(this);

        setSupportActionBar(mTb);//设置标题栏

        ActionBar actionBar = getSupportActionBar();//获取标题栏
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);//显示HomeAsUp按钮
            actionBar.setHomeAsUpIndicator(R.mipmap.ic_drawer);//设置HomeAsUp按钮图标
        }

        //设置DrawerLayout的菜单布局Navigation
        mNavigation.setCheckedItem(R.id.holder);//设置默认选中项
        mNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mDl.closeDrawers();
                return true;
            }
        });

        //给FloatingActionButton设置点击事件
        mAcb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "you clicked floatingActionBar", Snackbar.LENGTH_SHORT)
                        .setAction("showtoast", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showToast("you clicked ...");
                            }
                        })
                        .show();
            }
        });

        //初始化水果数据
        initFruitData();
        //给recyclerView设置布局样式和适配器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mFruitAdapter = new FruitAdapter(fruitList);
        mRecyclerView.setAdapter(mFruitAdapter);
    }

    //toolbar的menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    //toolbar上各个按钮点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.up:
                showToast("you clicked up");
                break;
            case R.id.delete:
                showToast("you clicked delete");
                break;
            case R.id.add:
                showToast("you clicked add");
                break;
            case android.R.id.home:
                mDl.openDrawer(GravityCompat.START);
                break;
            default:
                break;
        }
        return true;
    }

    //弹吐司
    private Toast mToast;

    public void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }

    //初始化水果数据
    private void initFruitData() {
        fruitList.clear();
        for (int i = 0; i <50; i++) {
            Random random=new Random();
            int index=random.nextInt( arr.length);
            Fruit fruit = new Fruit(arr[index], arrId[index]);
            fruitList.add(fruit);
        }
    }
}

转载于:https://my.oschina.net/u/3620480/blog/1499666

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值