[英]How to avoid using Reflection with RecyclerView
我做了一個RecyclerView,我想用不同的數據填充RecyclerView中的每個項目(一個視圖將獲得Resources String.xml
Text數據和Resources Drawable
Images)。 String.xml
每個字符串String.xml
被命名為cat1 ... cat2 ... catn以適合RecyclerView項目1 ... 2 ... n。
我使用的方法使用了大量的Reflection,是否還有另一種方法我無法弄清楚它更有效,更便宜? 我使用RecyclerView的全部要點是它便宜一些!
此方法查找特定字符串名稱的ID
public static int getStringIdentifier(Context context, String name) {
return context.getResources().getIdentifier(name, "string", context.getPackageName());
}
此方法基於RecylerView中位置的ID來構建資源名稱。 通過調用上面發布的方法獲取ID,然后字符串進行設置
public void bind(int index){
String resourceName = ("cat"+ (index + 1));
int ResourceId = getStringIdentifier(mContext, resourceName);
String catNameTitle = mContext.getResources().getString(resourceId);
test.setText(catNameTitle);
}
使用字符串數組而不是字符串來獲取貓的名字列表。
在您的strings.xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="cats">
<item>Cat1's name</item>
<item>Cat2's name</item>
<item>Cat3's name</item>
</string-array>
</resources>
獲取cat列表,並將該列表注入RecyclerView.Adapter
(或者在初始化適配器時簡單地將其獲取)。
String[] catNames = mContext.getResources().getStringArray(R.array.cats);
然后,在您的bind(int)
方法中:
public void bind(int index) {
test.setText(cats[index]);
}
將此方法放入您的recyclerview中以停止反映項目
override fun getItemViewType(position: Int): Int {
return position
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.