美文网首页
RecyclerView+intent使用

RecyclerView+intent使用

作者: Ivy枫 | 来源:发表于2019-09-30 13:32 被阅读0次

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

相关文章

网友评论

      本文标题:RecyclerView+intent使用

      本文链接:https://www.haomeiwen.com/subject/legcpctx.html