Wednesday, February 1, 2017

Get resource id by resource name

Tags

Example you have a picture name pic1.jpg in drawalbe folder. You can access your picture by use resource id R.drawable.pic1.
But if you want to access resource id by known the resource name, you can create custom method to access the resource id.


1.activity_main.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:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="300dp" />
</LinearLayout>

2.MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.text.Spannable;
import android.widget.ImageView;
import java.lang.reflect.Field;

public class MainActivity extends Activity {
    Spannable.Factory spannableFactory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setBackgroundResource(getResId("pic1", R.drawable.class));
    }

    private int getResId(String resName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(resName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}


EmoticonEmoticon