ListView和RecyclerView是Android开发中常用的两个模块,本文来简单介绍一下它们的基本使用方法,主要模块:
- TabLayout
- ViewPager
- Fragment
- ListView
- RecyclerView
1. 效果
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
<?xml version="1.0" encoding="utf-8"?>
<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
<?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="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
<?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">
<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
<?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"
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>