ListView和RecyclerView的简单使用

ListView和RecyclerView是Android开发中常用的两个模块,本文来简单介绍一下它们的基本使用方法,主要模块:

  • TabLayout
  • ViewPager
  • Fragment
  • ListView
  • RecyclerView

    文章目录

    • 1. 效果
    • 2. 文件目录
    • 3. 配置
    • 4. layout布局
      • 4.1 activity_main.xml
      • 4.2 fragment_list.xml
      • 4.3 fragment_recycler.xml
      • 4.4 item_layout.xml
    • 5. Java文件
      • 5.1 MainActivity.java
      • 5.2 FragmentList.java
      • 5.3 ListviewAdapter
      • 5.4 FragmentRecycler.java
      • 5.5 RecyclerviewAdapter.java

1. 效果

ListView和RecyclerView的简单使用_第1张图片

2. 文件目录

ListView和RecyclerView的简单使用_第2张图片

3. 配置

由于使用了Material Design中的TabLayout,需要在app文件夹下build.gradle中的 dependencies声明一些依赖

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // Material Design
    implementation 'com.google.android.material:material:1.1.0'
    // RecyclerView
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

4. layout布局

4.1 activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/main_tab"
        android:layout_width="match_parent"
        android:layout_height="36dp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

LinearLayout>

4.2 fragment_list.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/frag_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
LinearLayout>

4.3 fragment_recycler.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

        <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/frag_recyc"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
LinearLayout>

4.4 item_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/todo"
        android:src="@drawable/test_img" />

    <TextView
        android:id="@+id/item_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/this_is_text"
        android:textSize="36sp" />


LinearLayout>

5. Java文件

5.1 MainActivity.java

package com.example.list_recycler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    // 声明用到的组件
    private TabLayout tabLayout;
    private ViewPager viewPager;
    final List<Fragment> fragmentList = new ArrayList<>();
    final List<String> stringList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 绑定组件
        initView();
        // 添加显示的选项
        stringList.add("ListView");
        stringList.add("RecyclerView");
        // 添加展示的数据
        String[] data = {"111", "222", "333", "444", "555", "666", "777", "888", "999", "1000"};
        int[] images = {R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img, R.drawable.test_img};
        List<Map<String, Object>> list_map = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            // 创建一个键值对的Map集合,用来存放名字和头像
            Map<String, Object> items = new HashMap<>();
            // 放入图像, 根据下标获取数组
            items.put("pic", images[i]);
            // 放入文字, 根据下标获取数组
            items.put("name", data[i]);
            // 把这个存放好数据的Map集合放入到list_map中
            list_map.add(items);
        }
        // 添加显示的fragment
        fragmentList.add(new FragmentList(list_map));
        fragmentList.add(new FragmentRecycler(list_map));
        // 设置viewpager的适配器
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return stringList.get(position);
            }
        });
        // 加载viewpager
        tabLayout.setupWithViewPager(viewPager);
    }

    private void initView() {
        tabLayout = findViewById(R.id.main_tab);
        viewPager = findViewById(R.id.main_viewpager);
    }
}

5.2 FragmentList.java

package com.example.list_recycler;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.List;
import java.util.Map;

public class FragmentList extends Fragment {
    private final List<Map<String, Object>> list_map;

    public FragmentList(List<Map<String, Object>> name) {
        list_map = name;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_list, null);
        ListviewAdapter adapter = new ListviewAdapter(list_map);
        ListView listView = view.findViewById(R.id.frag_list);
        // 设置适配器
        listView.setAdapter(adapter);
        // 点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getContext(), "点击了:" + (position + 1), Toast.LENGTH_SHORT).show();
            }
        });
        // 长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getContext(), "长按了:" + (position + 1), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        return view;
    }
}

5.3 ListviewAdapter

package com.example.list_recycler;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ListviewAdapter extends BaseAdapter {
    private final List<Map<String, Object>> list_map;

    public ListviewAdapter(List<Map<String, Object>> list_map) {
        this.list_map = list_map;

    }

    @Override
    public int getCount() {
        return list_map.size();
    }

    @Override
    public Object getItem(int position) {
        return list_map.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
        }
        TextView textView = convertView.findViewById(R.id.item_text);
        ImageView imageView = convertView.findViewById(R.id.item_image);
        textView.setText(Objects.requireNonNull(list_map.get(position).get("name")).toString());
        imageView.setImageResource(Objects.requireNonNull((Integer) list_map.get(position).get("pic")));
        return convertView;
    }
}

5.4 FragmentRecycler.java

package com.example.list_recycler;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class FragmentRecycler extends Fragment {
    private final List<Map<String, Object>> list_map;

    public FragmentRecycler(List<Map<String, Object>> list_map) {
        this.list_map = list_map;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_recycler, null);
        RecyclerView recyclerView = view.findViewById(R.id.frag_recyc);
        RecyclerviewAdapter adapter = new RecyclerviewAdapter(list_map);
        recyclerView.setAdapter(adapter);
        // 线性布局
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), DividerItemDecoration.VERTICAL));
        return view;
    }
}

5.5 RecyclerviewAdapter.java

package com.example.list_recycler;

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 androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
    private final List<Map<String, Object>> list_map;

    public RecyclerviewAdapter(List<Map<String, Object>> list_map) {
        this.list_map = list_map;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //创建ViewHolder,返回每一项的布局
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
        return new MyViewHolder(view);
    }

    // 通过holder设置TextView,ImageView的内容
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        holder.textView.setText(Objects.requireNonNull(list_map.get(position).get("name")).toString());
        holder.imageView.setImageResource(Objects.requireNonNull((Integer) list_map.get(position).get("pic")));
        // 点击事件
        holder.item_View.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "点击了" + (position + 1), Toast.LENGTH_SHORT).show();
            }
        });
        // 长按事件
        holder.item_View.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(v.getContext(), "长按了" + (position + 1), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

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

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private final ImageView imageView;
        private final TextView textView;
        private final View item_View;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            this.item_View = itemView;
            this.imageView = itemView.findViewById(R.id.item_image);
            this.textView = itemView.findViewById(R.id.item_text);
        }
    }
}

你可能感兴趣的:(Android开发)