سؤال

أريد الوصول إلى مورد مثل سلسلة أو قابلة للسحب باسمها وليس معرف INT.

ما هي الطريقة التي سأستخدمها لهذا؟

هل كانت مفيدة؟

المحلول

سيكون شيئًا مثل:

R.drawable.resourcename

تأكد من عدم امتلاكك Android.R مساحة الاسم التي تم استيرادها لأنها يمكن أن تخلط بين Eclipse (إذا كان هذا ما تستخدمه).

إذا لم ينجح ذلك ، فيمكنك دائمًا استخدام سياق getResources طريقة ...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

أين this.context يعاني من ذلك ك Activity, Service أو أي دولة أخرى Context الفئة الفرعية.

تحديث:

إذا كان الاسم الذي تريده ، Resources الفصل (عاد بواسطة getResources()) لديه getResourceName(int) الطريقة ، و getResourceTypeName(int)?

تحديث 2:

ال Resources الفصل لديه هذه الطريقة:

public int getIdentifier (String name, String defType, String defPackage) 

الذي يعيد عدد صحيح لاسم المورد المحدد ، اكتب وحزمة.

نصائح أخرى

إذا فهمت بشكل صحيح ، هذا ما تريده

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

حيث "هذا" هو نشاط ، مكتوب فقط للتوضيح.

في حال كنت تريد سلسلة في STRINGS.xml أو معرف لعنصر واجهة المستخدم ، بديلاً "يمكن رسمه"

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

أحذرك من أن هذه الطريقة في الحصول على المعرفات بطيئة حقًا ، واستخدم فقط عند الحاجة.

رابط إلى الوثائق الرسمية: الموارد.

int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());

طريقة بسيطة للحصول على معرف الموارد من السلسلة. هنا ResourCename هو اسم Resource ImageView في مجلد Drawable والذي يتم تضمينه في ملف XML أيضًا.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);

Kotlin Version عبر Extension Function

للعثور على معرف مورد باسمه في Kotlin ، أضف مقتطفًا أدناه في ملف Kotlin:

extensionfunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

الآن يمكن الوصول إلى جميع معرفات الموارد حيثما كان لديك مرجع سياق باستخدام resIdByName طريقة:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    

أود أن أقترح عليك استخدام طريقتي للحصول على معرف مورد. إنها أكثر كفاءة ، من استخدام طريقة getIdentIdier () ، وهي بطيئة.

هذا هو الرمز:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> с) {

    Field field = null;
    int resId = 0;
    try {
        field = с.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}

لقد وجدت هذه الفئة مفيد جدا للتعامل مع الموارد. إنه يحتوي على بعض الطرق المحددة للتعامل مع الأبعاد والألوان والسحب والسلاسل ، مثل هذه:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}

بالإضافة إلى حل Lonkly

  1. انظر التأملات وإمكانية الوصول الميداني
  2. المتغيرات غير الضرورية

طريقة:

/**
 * lookup a resource id by field name in static R.class 
 * 
 * @author - ceph3us
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с            - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> с)
                     throws android.content.res.Resources.NotFoundException {
    try {
        // lookup field in class 
        java.lang.reflect.Field field = с.getField(variableName);
        // always set access when using reflections  
        // preventing IllegalAccessException   
        field.setAccessible(true);
        // we can use here also Field.get() and do a cast 
        // receiver reference is null as it's static field 
        return field.getInt(null);
    } catch (Exception e) {
        // rethrow as not found ex
        throw new Resources.NotFoundException(e.getMessage());
    }
}
// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top