简体   繁体   中英

How to avoid using Reflection with RecyclerView

I made a RecyclerView and I want to populate each item in the RecyclerView with different data (A view will be given Text data from Resources String.xml and Images from Resources Drawable ). Each string in String.xml is named cat1...cat2...catn to fit into RecyclerView items 1...2...n.

The method I am using uses a lot of Reflection, is there another way that I can't figure out that is more efficient and less expensive? The whole point in me using RecyclerView was that it was less expensive!!

This method finds the ID for a specific string name

    public static int getStringIdentifier(Context context, String name) {
     return context.getResources().getIdentifier(name, "string", context.getPackageName());
    }

This method builds the resource name based on the id for the position in the RecylerView. Gets the Id by calling the method posted above, then the string then sets it

    public void bind(int index){
        String resourceName = ("cat"+ (index + 1));

        int ResourceId = getStringIdentifier(mContext, resourceName);
        String catNameTitle = mContext.getResources().getString(resourceId);
        test.setText(catNameTitle);
    }

Use string-array instead of string to get a list of cat's name.

In your 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>

Get the list of cat and inject the list to the RecyclerView.Adapter (or simply get it when initializing the adapter).

String[] catNames = mContext.getResources().getStringArray(R.array.cats);

Then, in you bind(int) method:

public void bind(int index) {
    test.setText(cats[index]);
}

put this method into your recyclerview for stop reflecting items

override fun getItemViewType(position: Int): Int {
    return position
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM