RecyclerView CardView的基本使用

RecyclerView  看Java Code Geeke上說的是他比ListView更加的靈活,
我們都知道如何在我們的應用程序中使用列表視圖,我們知道如果我們想增加ListView的表現,我們可以使用一個模式被稱爲ViewHolder。該模式由一個簡單的類,它擁有UI組件的引用爲ListView中的每一行。以便減少對findById的使用。



按照我的對代碼順序進行描述代碼吧。首先這是一個Demo,一共展示的是三種形式。我們創建一個MainActivity作用就是分別可以切換這三種形式,同時傳遞一個Intent地址;

一、MainActivity

package com.example.hejingzhou.cardlistdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button mbtList,mbtSquare,mbtStaggered;
    private static int Type_List = 0;
    private static int Type_Square = 1;
    private static int Type_Staggered = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏
        setContentView(R.layout.activity_main);
        findViewById();
        mbtList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent listIntent = new Intent(MainActivity.this, TypeActivity.class);
                listIntent.putExtra("type", Type_List);
                startActivity(listIntent);
            }
        });
        mbtSquare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent listIntent = new Intent(MainActivity.this, TypeActivity.class);
                listIntent.putExtra("type",Type_Square);
                startActivity(listIntent);
            }
        });
        mbtStaggered.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent listIntent = new Intent(MainActivity.this, TypeActivity.class);
                listIntent.putExtra("type",Type_Staggered);
                startActivity(listIntent);
            }
        });
    }

    private void findViewById() {
        mbtList = (Button)findViewById(R.id.buttonList);
        mbtSquare = (Button)findViewById(R.id.buttonSquare);
        mbtStaggered = (Button)findViewById(R.id.buttonStaggered);
    }
}


這個很簡單,然後可以跳轉到TypeActivity這個類中,這個類就是判斷傳進的Intent值是幾,然後針對相應的代碼進行相應的響應。

二、TypeActivity

這個類中需要使用今天的主角RecyclerView類但是這個類你是沒辦法import出來的你需要在build.gradle中添加   compile 'com.android.support:recyclerview-v7:21.0.+'      後才能引入這個類。

package com.example.hejingzhou.cardlistdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.WindowManager;


public class TypeActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;//創建佈局管理器
    
    <pre name="code" class="plain">    private String[]  title = {
    "小鳥小鳥小鳥小鳥小鳥小鳥小鳥小鳥",
    "音樂音樂音樂音樂",
    "應用應用應用應用",
    "花朵花朵花朵花朵",
    "遊戲遊戲遊戲遊戲",
    "查找查找查找查找",
    "相冊相冊相冊相冊"
     };


    private int[] pic = {R.mipmap.aa1, R.mipmap.aa0, R.mipmap.aa2, R.mipmap.aa3, R.mipmap.aa4, R.mipmap.aa5, R.mipmap.aa6};/圖片資源數組

    private final static int Type_List = 0;
    private final static int Type_Square = 1;
    private final static int Type_Staggered = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_type);
        mRecyclerView = (RecyclerView)findViewById(R.id.RecyclerView_list);//佈局管理器與佈局管理控件關聯
        if(getIntent().getIntExtra("type",0) == Type_List)//Type of List
        {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);//創建新的線性佈局管理對象
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);//將線性佈局管理方向設置爲垂直
            mRecyclerView.setLayoutManager(linearLayoutManager);
        }else if(getIntent().getIntExtra("type",0) == Type_Square) {
            mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
        }else if(getIntent().getIntExtra("type",0) == Type_Staggered){
            mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL));
        }
        mRecyclerView.setAdapter(new RecyclerViewAdapter(pic, title, this));//寫到這裏的時候就要寫一個適配器類了,和ListView類似
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }
}<span style="color:#ff0000;">
</span>



三、RecyclerViewAdapter

在寫這個類之前需要一個CardView的佈局文件了(layout_card_view.xml)
再寫這個佈局文件的時候同樣你是不會找到這個CardView 類的,你需要進行再需要在build.gradle中添加一句  compile 'com.android.support:cardview-v7:21.0.+'    纔可以引用這個類的

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:id="@+id/cv_item"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardCornerRadius="4dp"
    card_view:cardBackgroundColor="#c32136"
    card_view:cardElevation="4dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <ImageView
            android:id="@+id/iv_pic"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_weight="1"

            />
        <TextView
            android:id="@+id/tv_text"
            android:padding="15dp"
            android:textColor="#ffffff"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

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


package com.example.hejingzhou.cardlistdemo;

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 android.widget.Toast;

/**
 * Created by Hejingzhou on 2016/2/21.
 */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.NormalViewHolder> {

    private LayoutInflater mLayoutInflater;//創建佈局填充器
    private Context mcContext;
    private String[] mTitle;
    private int[] mPic;

    public RecyclerViewAdapter(int[] mPic, String[] mTitle, Context mcContext) {
        this.mPic = mPic;
        this.mTitle = mTitle;
        this.mcContext = mcContext;
        mLayoutInflater = LayoutInflater.from(mcContext);
    }

    /**
     * ViewHolder通過保存item中使用到的控件的引用來減少findViewById的調用,以此使ListView滑動得更加順暢。
     */
    public class NormalViewHolder extends RecyclerView.ViewHolder
    {
        TextView mteTextView;
        CardView mcCardView;
        ImageView mImageView;
        public NormalViewHolder(View itemView) {
            super(itemView);
            mteTextView = (TextView) itemView.findViewById(R.id.tv_text);
            mcCardView = (CardView)itemView.findViewById(R.id.cv_item);
            mImageView = (ImageView)itemView.findViewById(R.id.iv_pic);
        }
    }

    public NormalViewHolder onCreateViewHolder(ViewGroup viewGroup,int viewType)
    {
        return new NormalViewHolder(mLayoutInflater.inflate(R.layout.layout_card_view,viewGroup,false));
    }

    /**
     * 標題 圖片  Toast綁定
     * @param holder  持有對象
     * @param position  位置 數組下標
     */
    @Override
    public void onBindViewHolder(RecyclerViewAdapter.NormalViewHolder holder, final int position) {
        holder.mteTextView.setText(mTitle[position]);
        holder.mImageView.setBackgroundResource(mPic[position]);
        holder.mcCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mcContext,mTitle[position], Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 獲得條目數
     * @return  條目數
     */
    @Override
    public int getItemCount() {
        return mTitle == null ?0:mTitle.length;
    }
}


Ok了


















源代碼 :http://download.csdn.net/detail/csdnhejingzhou/9438743

發佈了56 篇原創文章 · 獲贊 26 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章