如何获取与TextView关联的字符串资源的ID?

时间:2017-10-31 12:24:48

标签: android textview android-resources

我可以访问TextView实例,获取它的资源ID并通过getResources().getResourceEntryName()获取它的资源名称,但我似乎无法找到一种方法来获取与之关联的字符串的id。

如何动态获取与TextView关联的字符串资源的ID?

2 个答案:

答案 0 :(得分:1)

你做不到。如果您调用TextViewsetText(int resid)不会存储字符串资源的ID。所有这些重载方法都是从资源中获取String并调用setText(CharSequence text)方法。

答案 1 :(得分:0)

我唯一可行的解​​决方法是将布局xml中的T​​extView实例的+id与字符串的name相匹配,然后使用Resources将两者配对:

/**
     * finds a string id matching a text view id name and returns the value
     * @param textView - text view
     * @param context  - the context
     * @param locale   - the locale string
     * @return  String - resource string if found, empty string otherwise
     */
    public  static String getTextViewStringFromResources(TextView textView,Context context,String locale){
        String result = "";
        final int textViewID = textView.getId();

        if(textViewID <= 0){
            Log.e(TAG,"invalid id for textView " + textView + " text = " + textView.getText());
            result = textView.getText().toString();
            return result;
        }
        //get resources (re-usable)
        final Resources resources = getLocalizedResources(context,locale);
        // get textViews id
        final String entryName = resources.getResourceEntryName(textView.getId());
        // get the string id !! must match the textview id !!
        final int stringID = resources.getIdentifier(entryName,"string",context.getPackageName());
        //return string value for string id found by textview id
        try{
            result = resources.getString(stringID);
        }catch (Resources.NotFoundException e){
            Log.e(TAG,"couldn't find a string id for " + entryName);
            Log.e(TAG,e.getMessage());
        }
        return result;
    }

//!! requires minSDK 17
    @NonNull
    public static Resources getLocalizedResources(Context context, String locale) {
        Locale desiredLocale = new Locale(locale);
        Configuration conf = context.getResources().getConfiguration();
        conf.setLocale(desiredLocale);
        Context localizedContext = context.createConfigurationContext(conf);
        return localizedContext.getResources();
    }

交换部分基于交换文本字段的Gunhan Sancar's method

这有效,但它几乎是一个黑客。

最终我还需要以编程方式更改Google手写输入语言,并且该Juuso's ADB Change Language应用程序非常方便。

作为参考,这里有一个使用Juuso方法的功能:

final String TAG = "ChangeLanguage"
//change language utils "kindly borrowed" from net.sanapeli.adbchangelanguage: brilliant little app!

    /**
     * updates a Configuration with a list of Locales
     * @param configuration - a configuration to updated
     * @param arrayList - an ArrayList of Locale instances
     * @return the updated configuration
     */
    @TargetApi(24)
    public static Configuration addLocalesToConfiguration(Configuration configuration, ArrayList<Locale> arrayList) {
        configuration.setLocales(new LocaleList((Locale[]) arrayList.toArray(new Locale[arrayList.size()])));
        return configuration;
    }

    /**
     * Change the system language
     * @param lanaguageList - a list of Locale instances to change to
     */
    public static void changeLanguages(ArrayList<Locale> lanaguageList){
        try {
            Class cls = Class.forName("android.app.ActivityManagerNative");
            Method method = cls.getMethod("getDefault", new Class[0]);
            method.setAccessible(true);
            Object invoke = method.invoke(cls, new Object[0]);
            method = cls.getMethod("getConfiguration", new Class[0]);
            method.setAccessible(true);
            Configuration configuration = (Configuration) method.invoke(invoke, new Object[0]);
            configuration.getClass().getField("userSetLocale").setBoolean(configuration, true);
            if (VERSION.SDK_INT >= 24) {
                configuration = addLocalesToConfiguration(configuration, lanaguageList);
            } else {
                configuration.locale = (Locale) lanaguageList.get(0);
            }
            Method method2 = cls.getMethod("updateConfiguration", new Class[]{Configuration.class});
            method2.setAccessible(true);
            method2.invoke(invoke, new Object[]{configuration});
            Log.d(TAG,"locale updated to" + lanaguageList.get(0).toString());
        } catch (Exception e) {
            Log.e(TAG,"error changing locale (double check you're granted permissions to the app first: pm grant your.app.package.here android.permission.CHANGE_CONFIGURATION )");
            e.printStackTrace();
        }
    }

请务必向您的应用授予CHANGE_CONFIGURATION

这是使用Android 7.1.1进行测试的,但请注意,在某些构建条件下找不到getConfiguration(API不同)时,它会在Android 8.0上失败(可能会向上)。

该方法需要一个Locale对象的ArrayList,其中包含您要更改的语言: 例如

ArrayList<Locale> fr = new ArrayList<Locale>();
fr.add(new Locale("fr"));
fr.add(new Locale("en"));

ArrayList<Locale> en = new ArrayList<Locale>();
en.add(new Locale("en"));
en.add(new Locale("fr"));

确保语言也已安装在设备上。

如果您有其他改进建议,我非常乐意更新答案