本意是解决RecyclerView动态添加背景后item高度不正确的bug。一开始以为是RecyclerView的问题,后来发现是background.xml多加了padding。把背景xml的padding删掉后就正常了。但demo写都写了存一下吧。
需求:根据item在RecyclerView的不同位置添加不同背景。
解:给RecyclerView写一个adapter,通过重载onBindViewHolder设置背景。
MainActivity.java background.xml activity_main.xml<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/cats_recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginHorizontal="16dp" android:nestedScrollingEnabled="false"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="click me"> </Button> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
另外碰到了gradle的一个报错: 2 files found with path 'META-INF/androidx.localbroadcastmanager_localbroadcastmanager.version'.
原因是一开始用的android support的RecycleView,android support和androidx不兼容,都改成androidx就好了。
plugins { alias(libs.plugins.android.application) } android { namespace = "com.example.myapplication" compileSdk = 34 defaultConfig { applicationId = "com.example.myapplication" minSdk = 28 targetSdk = 34 versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } } dependencies { implementation("androidx.appcompat:appcompat:1.1.0") implementation(libs.material) implementation("androidx.constraintlayout:constraintlayout:1.1.3") implementation("androidx.recyclerview:recyclerview:1.1.0") }build.gradle.kts
标签:xml,androidx,implementation,item,添加,android,RecyclerView From: https://www.cnblogs.com/capterlliar/p/18635973