RecyclerView+intent使用

RecyclerView+Intent传值使用

RecyclerView的基本步骤:

  1. 创建资源的实体类(Fruit类)
  2. 创建RecyclerView的子项布局(recycler_item.xml)
  3. 自定义适配器
  • 适配器要继承RecyclerView.Adapter<Fruit.ViewHodler>
  • 创建内部类ViewHolder继承RecyclerView.Holder,用来加载控件
  • 重写onCreatViewHolder()方法,加载recycler_item的布局,并创建一个ViewHolder实例
  • 重写onBindViewHolder()方法,将recyclerView的子项进行赋值
  • 重写getItemCount()方法

Fruit.class

package com.example.recyclerviewactivity;

public class Fruit {
    private String name;
    private int imageId;

    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }


    public int getImageId() {
        return imageId;
    }

}

既然使用了Intent传值,就需要至少2个Activity,创建一个MainActivity用来显示所有水果数据,一个FruitActivity用来显示具体的水果信息

activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>

recycler_item.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="wrap_content"
    >

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_apple"
        />

    <TextView
        android:id="@+id/fruit_name"
        android:text="apple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

</LinearLayout>

自定义适配器FruitAdapter

package com.example.recyclerviewactivity;

import android.support.annotation.NonNull;
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;

import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
    private List<Fruit> fruits;

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

    static public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
        View fruitView;


        //加载控件
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            fruitView = itemView;
            fruitName = itemView.findViewById(R.id.fruit_name);
            fruitImage = itemView.findViewById(R.id.fruit_image);
        }
    }

    //创建ViewHolder实例
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
        final ViewHolder holder = new ViewHolder(view);

        //给recycler_item添加监听器
        holder.fruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int k = holder.getAdapterPosition();
                Fruit fruit1 = fruits.get(k);
                FruitActivity.actionStart(holder.fruitView.getContext(),fruit1.getName(),fruit1.getImageId());
                //Toast.makeText(v.getContext(), "你选中了" + fruit1.getName(), Toast.LENGTH_LONG).show();
            }
        });
        //给图片添加监听器
        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int k = holder.getAdapterPosition();
                Fruit fruit1 = fruits.get(k);
                FruitActivity.actionStart(holder.fruitView.getContext(),fruit1.getName(),fruit1.getImageId());
                //Toast.makeText(v.getContext(), "你选中了" + fruit1.getName(), Toast.LENGTH_LONG).show();
            }
        });
        return holder;
    }

    //给recyclerView子项赋值
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, int i) {
        Fruit fruit = fruits.get(i);
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
    }

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

}

MainActivity.class

package com.example.recyclerviewactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    public ArrayList<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        RecyclerView recyclerView = findViewById(R.id.recycler_layout);//获取RecyclerView实例
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);//指定recyclerView的布局方式为线性布局
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);//创建adapter实例
        recyclerView.setAdapter(adapter);
    }


    //初始化水果数据
    public void init(){
        for (int i = 0; i < 3; i++) {
            Fruit apple = new Fruit("apple",R.drawable.ic_apple);
            fruitList.add(apple);
            Fruit banana= new Fruit("banana",R.drawable.ic_banana);
            fruitList.add(banana);
            Fruit grape = new Fruit("grape",R.drawable.ic_grape);
            fruitList.add(grape);
            Fruit mango = new Fruit("mango",R.drawable.ic_mango);
            fruitList.add(mango);
            Fruit orange = new Fruit("orange",R.drawable.ic_orange);
            fruitList.add(orange);
            Fruit strawberry = new Fruit("strawberry",R.drawable.ic_strawberry);
            fruitList.add(strawberry);
            Fruit watermelon = new Fruit("watermelon",R.drawable.ic_watermelon);
            fruitList.add(watermelon);
        }
    }
}

在适配器中,设置了每个recyclerViewItem和水果picture的点击事件,点击之后会跳转到FruitActivity的活动中,并且通过intent将图片和水果名字传到FruitActivit活动中。

activity_fruit.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.32" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fruit_image"
        app:layout_constraintVertical_bias="0.22000003" />
</android.support.constraint.ConstraintLayout>

FruitActivity.class

package com.example.recyclerviewactivity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class FruitActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit);
        ImageView imageView = findViewById(R.id.fruit_image);
        TextView textView = findViewById(R.id.fruit_name);
        Intent intent = getIntent();
        textView.setText(intent.getStringExtra("fruitName"));
        imageView.setImageResource(intent.getExtras().getInt("fruitId"));
    }

    public static void actionStart(Context context,String fruitName,int fruitId) {
        Intent intent = new Intent(context,FruitActivity.class);   //创建intent实例
        intent.putExtra("fruitName",fruitName);//放入要传递的参数
        intent.putExtra("fruitId",fruitId);
        context.startActivity(intent);
    }
}

当要传递的参数很多或者2个人分别写不同的activity时,第一个活动不知道要传些什么参数,自己去看代码又太复杂,这时在FruitActivity中创建actionStart()方法,当MainActivity调用方法时,就知道要传哪些参数了,在FruitActivity中通过getIntent()取出intent,通过intent的getStringExtra()方法得到水果名字,getExtras().getInt()得到水果图片id。

运行结果:


Screenshot_1569763267.png

Screenshot_1569767009.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容