Android 利用getIdentifier()方法获取资源ID
/**
* 利用getIdentifier()方法获取资源ID
* 方法描述:
* getIdentifier(String name, String defType, String defPackage)
* 第一个参数:资源的名称
* 第二个参数:资源的类型(drawable,string等)
* 第三个参数:包名
*/
public class MainActivity extends Activity {
private Context mContext;
private ImageView mImageView;
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initUI();
}
private void initUI(){
mContext=this;
//获取图片资源的ID
mImageView=(ImageView) findViewById(R.id.imageView);
int drawableId = mContext.getResources().getIdentifier("ic_launcher","drawable", mContext.getPackageName());
mImageView.setImageResource(drawableId);
System.out.println("----> 获取到的图片资源 drawableId="+drawableId);
//获取字符串资源
mTextView=(TextView) findViewById(R.id.textView);
int stringId = mContext.getResources().getIdentifier("hello","string", mContext.getPackageName());
mTextView.setText(stringId);
System.out.println("----> 获取到的字符串资源 stringId="+stringId);
}
}
main_activity.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="利用getIdentifier()方法获取资源ID" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip" />
</RelativeLayout>
strings.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">TestGetIdentifier</string>
</resources>