在Android开发的过程中我们需要动态的根据一个资源名获得到对应的资源id,我们可以使用getResources().getIdentifier()方法来获取该id, 然后通过该id进行相应的操作。
使用方法如下:
1、工程目录如下:
2、MainActivity代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources resources = getResources();
//获取布局文件的Id
int mainLayout = resources.getIdentifier("activity_main", "layout", getPackageName());
setContentView(mainLayout);
//获取TextView 的id
int txtId = resources.getIdentifier("author", "id", getPackageName());
//获取字符串id
int strId = resources.getIdentifier("author", "string", getPackageName());
//获取Drawable id
int drawableId = resources.getIdentifier("text_bg", "drawable", getPackageName());
TextView textView = (TextView) findViewById(txtId);
textView.setText(strId);
textView.setBackground(ContextCompat.getDrawable(this, drawableId));
//ImageView id
int imgId = resources.getIdentifier("launcher_icon", "id", getPackageName());
//mipmap id
int mipmapId = resources.getIdentifier("ic_launcher", "mipmap", getPackageName());
ImageView imageView = (ImageView) findViewById(imgId);
imageView.setImageResource(mipmapId);
}
}
3、布局文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:padding="5dp" />
<ImageView
android:id="@+id/launcher_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_below="@id/author" />
</RelativeLayout>
4、strings.xml字符串资源代码如下:
<resources>
<string name="app_name">ResouceId</string>
<string name="author">Owen Chan Blog</string>
</resources>