使用了Android的反思 [英] Using Reflection with Android

查看:143
本文介绍了使用了Android的反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到一个有趣的问题。我有4个字符串,我需要显示在随机的基础上应用。所以,我只是增加了串到我的string.xml并设置TextView的我展现文本

textView.setText(R.string.text_1);

或(如果随机数是2)

textView.setText(R.string.text_2);

我观察到的变化是刚刚在最后一个字符,使用反射所以试图


C类=的Class.forName(com.startpage.mobile.R $字符串);

场场= c.getDeclaredField(文_+ NUM); // num是1/2/3/4
的System.out.println( * 的*** + field.get(NULL));

现在的field.get(空)实际上返回ID(十六进制数在R.java)值,而不是字符串值,我期望的那样。

有没有办法使用反射来获取字符串的实际值或这是一件在android系统,我将不得不忍受?


解决方案

  getResources.getString(RESOURCEID);

I faced an interesting problem today. I have 4 strings which I need to show on app on random basis. So I simply added the strings to my string.xml and was setting my textview to show the text as

textView.setText(R.string.text_1);

or (if random number was 2)

textView.setText(R.string.text_2);

and so on

I observed that the change is just in last character, so tried using reflection

Class c = Class.forName("com.startpage.mobile.R$string");

Field field = c.getDeclaredField("text_"+num); //num is 1/2/3/4 System.out.println("**** "+field.get(null));

Now the field.get(null) actually return the Id (hexadecimal number in R.java) value instead of string value I would expect.

Is there a way to fetch actual value of string using reflection or this is something in android which I will have to live with?

解决方案

getResources.getString(resourceId);

这篇关于使用了Android的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆