Let's say I have an application with 2 themes: masculine and feminine. The themes simply change out the color palette and a few drawables to appeal to the user's preferred tastes.
Many thanks to http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html for his hints at making that work.
But now lets say I want to get a little cuter with the app and not only change the colors and drawables, but I also want to change the strings. For instance, I might want to add a pirate theme and then "Submit" would be "Arrrrgh!"
So, my basic question is: How can I change the strings throughout my app via user selectable themes?
Edit:
Making this up: the app has 12 buttons and 32 text views I'd like to have theme dependent and I'd like to accomplish this without a giant mapping or a slew of custom attrs.
All 3 of the current solutions will work. Looking for something cleaner though I don't know that such a beast exists.
Yes, it can be done, and here's how: first you'll have to define a theme attribute, like so:
<attr name="myStringAttr" format="string|reference" />
Then, in your themes, add this line
<item name="myStringAttr">Yarrrrr!</item>
or
<item name="myStringAttr">#string/yarrrrr</item>
You can then use this attribute in an XML file like so (note the ? instead of #).
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?attr/myStringAttr" />
or, from code, like so:
public CharSequence resolveMyStringAttr(Context context)
{
Theme theme = context.getTheme();
TypedValue value = new TypedValue();
if (!theme.resolveAttribute(R.attr.myStringAttr, value, true)) {
return null;
}
return value.string;
}
Let's say I have an application with 2 themes: masculine and feminine. The themes simply change out the color palette and a few drawables to appeal to the user's preferred tastes.
How about we pretend that you're doing something else? This is a design anti-pattern, associating particular colors based on gender (e.g., "girls like pink").
This is not to say that your technical objective is bad, just that this is a really stereotypical example.
For instance, I might want to add a pirate theme and then "Submit" would be "Arrrrgh!"
Only if "Cancel" maps to "Avast!".
How can I change the strings throughout my app via user selectable themes?
You have not said where those strings are coming from. Are they string resources? Database entries? Ones that you are retrieving from a Web service? Something else?
I will assume for the moment that these are string resources. By definition, you will need to have N copies of the strings, one per theme.
Since gender and piratical status are not things tracked by Android as possible resource set qualifiers, you can't have those string resources be in different resource sets. While they could be in different files (e.g., res/values/strings_theme1.xml), filenames are not part of resource identifiers for strings. So, you will wind up having to use some sort of prefix/suffix to keep track of which strings belong with which themes (e.g., #string/btn_submit_theme1).
If these strings are not changing at runtime -- it's just whatever is in your layout resource -- you could take a page from Chris Jenkins' Calligraphy library. He has his own subclass of LayoutInflater, used to overload some of the standard XML attributes. In his case, his focus is on android:fontFamily, where he supports that mapping to a font file in assets.
In your case, you could overload android:text. In your layout file, rather than it pointing to any of your actual strings, you could have it be the base name of your desired string resource, sans any theme identifier (e.g., if the real strings are #string/btn_submit_theme1 and kin, you could have android:text="btn_submit"). Your LayoutInflater subclass would grab that value, append the theme name suffix, use getIdentifier() on your Resources to look up the actual string resource ID, and from there get the string tied to your theme.
A variation on this would be to put the base name in android:tag instead of android:text. android:text might point to one of your real string resources, to help with GUI design and such. Your LayoutInflater would grab the tag and use that to derive the right string at runtime.
If you will be replacing text with other text pulled from theme-based string resources, you could isolate your get-the-string-given-the-base-name logic into a static utility method somewhere that you could apply.
While getting this right initially will take a bit of work, it will scale to arbitrary complexity, in terms of the number of affected UI widgets and strings. You still have to remember to add values for all themes for any new strings you define (bonus points for creating a custom Lint check or Gradle task for validating this).
Since a resource is just an int at heart you could store a number of them at runtime and them substitute them in procedurally as you use them.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="OK_NORMAL">Okay</string>
<string name="OK_PIRATE">Yaaarrrr!</string>
<string name="OK_NINJA">Hooooaaa!</string>
</resources>
public enum ThemeMode {
PIRATE,
NINJA,
NORMAL;
}
public class MyThemeStrings {
public static int OK_PIRATE = R.string.OK_PIRATE;
public static int OK_NINJA = R.string.OK_NINJA;
public static int OK_NORMAL = R.string.OK_NORMAL;
}
public setOkButtonText(ThemeMode themeMode) {
// buttonOk is instantiated elsewhere
switch (themeMode) {
case PIRATE:
buttonOk.setText(MyThemeStrings.OK_PIRATE);
break;
case NINJA:
buttonOk.setText(MyThemeStrings.OK_NINJA);
break;
default:
Log.e(TAG, "Unhandled ThemeMode: " + themeMode.name());
// no break here so it flows into the NORMAL base case as a default
case NORMAL:
buttonOk.setText(MyThemeStrings.OK_NORMAL);
break;
}
}
Although, having written all that, there is probably a better way to do all this through separate XML files. I'll look into it now and write a second solution if I find one.
Ok, I have a second option which may actually be easier to maintain and keep your code cleaner although it may be more resource hungry due to loading an array for each String. I've not benchmarked it but will offer it as another choice but I wouldn't use it if you offer too many theme choices.
public enum ThemeMode {
NORMAL(0),
PIRATE(1),
NINJA(2);
private int index;
private ThemeMode(int index) {
this.index = index;
}
public int getIndex() {
return this.index;
}
}
<resources>
<!-- ALWAYS define strings in the correct order according to
the index values defined in the enum -->
<string-array
name="OK_ARRAY">
<item>OK</item>
<item>Yaarrrr!</item>
<item>Hooaaaa!</item>
</string-array>
<string-array
name="CANCEL_ARRAY">
<item>Cancel</item>
<item>Naarrrrr!</item>
<item>Wha!</item>
</string-array>
</resources>
public setButtonTexts(Context context, ThemeMode themeMode) {
// buttons are instantiated elsewhere
buttonOk.setText(context.getResources()
.getStringArray(R.array.CANCEL_ARRAY)[themeMode.getIndex()]);
buttonCancel.setText(context.getResources()
.getStringArray(R.array.OK_ARRAY)[themeMode.getIndex()]);
}
So, I have not had a chance to test this, but from reading the file on Locale it looks like you can create your own location.
http://developer.android.com/reference/java/util/Locale.html
and help from another stackoverflow
Set Locale programmatically
A little bit of combination leads me to:
Locale pirate = new Locale("Pirate");
Configuration config = new Configuration();
config.locale = pirate;
this.getActivity().getBaseContext().getResources()
.updateConfiguration(config,
this.getActivity().getBaseContext().getResources().getDisplayMetrics());
I do believe this would let you have res/values-pirate/strings as an actual valid resource that would get used when you are a pirate. Any strings or settings you don't override would then revert to the res/values/... by default so you could do this for as many themes as you want. Again assuming it works.
Related
I have successfully completed a navigation into RecyclerViewAdapter to navigate many destinations by string Resource. Because I have many lists, and each TextView it's about separate fragment.
It's wonderful to do it. But I have a small problem. That's I have 2 string Resource, "en" English as a default and "ar" as a second language.
My app is working well when I use it by English locale. But it crashes when I use it by Arabic locale.
What I want is:
To control or force the app when it converts to Arabic to still use the default, which is English string resource.
Here's the RecyclerViewAdapter code block:
override fun onBindViewHolder(holder: SubSectionListHolder, position: Int) {
val item = dataset[position]
holder.subSectionView.text = context.resources.getString(item.subSectionSrcID)
holder.subSectionView.setOnClickListener {
val stringConvertToId = it.resources.getIdentifier(
context.resources.getString(item.subSectionSrcID).replace("\\s".toRegex(), ""),
"id",
context.packageName)
it.findNavController().navigate(stringConvertToId)
}
}
Here's sample of the navGraph tag:
<fragment
android:id="#+id/CreateOrder"
android:name=".PoCreateOrderFragment"
android:label="#string/btnStr_crtOrder"
tools:layout="#layout/fragment_po_create_order">
</fragment>
<fragment
android:id="#+id/ReceivedPreOrders"
android:name=".PoRcOrdersFragment"
android:label="#string/str_whPo_rcvdPrm"
tools:layout="#layout/fragment_po_rc_orders">
</fragment>
<fragment
android:id="#+id/DeferredPreOrders"
android:name=".PoDfOrdersFragment"
android:label="#string/str_whPo_dfrdPrm"
tools:layout="#layout/fragment_po_df_orders">
</fragment>
Here's sample of the default string Resource tag:
<string name="btnStr_crtOrder">Create Order</string>
<string name="str_whPo_rcvdPrm">Received PreOrders</string>
<string name="str_whPo_dfrdPrm">Deferred PreOrders</string>
Here's sample of the Arabic string Resource tag:
<string name="btnStr_crtOrder">إضافة طلب</string>
<string name="str_whPo_rcvdPrm">الطلبيات المستلمة</string>
<string name="str_whPo_dfrdPrm">الطلبيات المؤجلة</string>
To completely reach my idea to you.
This is really brittle (as you're finding out!) and you're just going to create headaches for yourself with this kind of complicated stuff. You should really keep the UI (e.g. the text being displayed) completely separate from the business logic (in this case, uniquely identifying each item and doing a specific action based on which one is clicked). The way you're doing it, it completely breaks whenever the display text is changed
You're already holding a list of items with a resource string ID, right? And looking them up by index using the RecyclerView position. If I were you, I'd just create a lookup associating each item with a hardcoded navigation resource ID.
You could make another list with all the navigation IDs and use position to grab the correct one. Or you could make a Map associating each string resource ID with its navigation ID:
val labelsToDestinations = mapOf(
R.string.btnStr_crtOrder to R.id.createOrder,
...
)
// in onBindViewHolder
holder.subSectionView.setOnClickListener {
val destination = labelsToDestinations[item.subSectionSrcID]
it.findNavController.navigate(destination)
}
That way, it doesn't matter what the value of the string resource is, you're just looking it up by the resource's ID. The value can change (different languages, different wording) and that doesn't matter.
Or just make it another property on the item (e.g. item.destinationId), like your label string ID already is. Personally, if I have a fixed set of things I need to define like this, I usually make an enum (you could use a sealed class if you want:
enum class DestinationItem(#StringRes labelId: Int, #IdRes navigationId: Int) {
CREATE_ORDER(R.string.btnStr_crtOrder, R.id.createOrder)
RECEIVED_PRE_ORDERS(R.string.str_whPo_rcvdPrm, R.id.receivedPreOrders)
...
}
val items = DestinationItem.values()
then you can generate your list of items from that, and you have access to all the important IDs on the item itself. You can easily change which resources they use without affecting anything else - you can use a different label resource to control the display, that won't affect the navigation ID because it's a completely separate property
I need some guidance with setting default theme for LatinIME on AOSP. I am not quite sure where this value is stored.
First I tried setting the theme in ThemeSettingsFragment.java located in LatinIME. So now everytime a theme was set or changed it would always pick mine. Later on I found out this class is only called when we open Keyboard themes in Settings (Language & Input -> Android Keyboard (AOSP) -> Appearance & layouts -> Theme). Resulting in theme being changed only IF we opened these view. My goal is to have my theme set when I build AOSP.
Next I suspected the value could be stored in some global configuration and that led me to class InputMethodManagerService.java where I found constant Settings.Secure.DEFAULT_INPUT_METHOD. But that didn't lead me anywhere worth while.
Anyone ever worked on something similar or knows the solution to my problem?
You can try making changes here : https://github.com/LineageOS/android_packages_inputmethods_LatinIME/blob/cm-14.1/java/src/com/android/inputmethod/keyboard/KeyboardTheme.java#L56-L58
I hope it helps.
Sanyam Jain is right to the point, adding few more details to it.
packages/inputmethods/LatinIME/java/src/com/android/inputmethod/keyboard/KeyboardTheme.java to be modified to change the default keyboard layout or you can add your custom layout there and also make sure the options added/changed correctly in packages/inputmethods/LatinIME/java/res/values/keyboard-themes.xml
In my case, I want material dark theme as default and first option in the keyboard layout settings. below are the changes I made,
KeyboardTheme.java
public static final int DEFAULT_THEME_ID = THEME_ID_LXX_DARK;
private static KeyboardTheme[] AVAILABLE_KEYBOARD_THEMES;
/* package private for testing */
static final KeyboardTheme[] KEYBOARD_THEMES = {
new KeyboardTheme(THEME_ID_LXX_DARK, "LXXDark", R.style.KeyboardTheme_LXX_Dark,
// This has never been selected as default theme.
Build.VERSION_CODES.LOLLIPOP),
new KeyboardTheme(THEME_ID_ICS, "ICS", R.style.KeyboardTheme_ICS,
// This has never been selected because we support ICS or later.
VERSION_CODES.BASE),
new KeyboardTheme(THEME_ID_KLP, "KLP", R.style.KeyboardTheme_KLP,
// Default theme for ICS, JB, and KLP.
VERSION_CODES.ICE_CREAM_SANDWICH),
new KeyboardTheme(THEME_ID_LXX_LIGHT, "LXXLight", R.style.KeyboardTheme_LXX_Light,
// Default theme for LXX.
VERSION_CODES.BASE),
};
In keyboard-themes.xml
<string-array name="keyboard_theme_names" translatable="false">
<item>#string/keyboard_theme_material_dark</item>
<item>#string/keyboard_theme_material_light</item>
<item>#string/keyboard_theme_holo_white</item>
<item>#string/keyboard_theme_holo_blue</item>
</string-array>
<!-- An element must be a keyboard theme id of
{#link com.android.inputmethod.keyboard.KeyboardTheme#THEME_ID_ICS} etc. -->
<integer-array name="keyboard_theme_ids" translatable="false">
<item>4</item>
<item>3</item>
<item>2</item>
<item>0</item>
</integer-array>
Let's say, on my API call I have a parameter that's called color. Is it possible to edit or modify an existent R.colors.color to assign the color from the API result?
As an example:
I make a call to my API and it returns green, now I want to load my app with i.e (green Toolbar, green TextView color, etc.), is that possible?
My first thought was:
Create a item on colors.xml called demo then assign it a default color, then use this demo color wherever I want (Button, TextView, etc.) Then I thought it could be possible to change this value programmatically with the result from the API so I wouldn't need to create a SharedPreferences or something like that and for avoiding more code.
As #Y.S. said to me
Unfortunately, you WILL have to set the color of the text or view manually everywhere ... :(
I would like if there is other way to do it, since I don't know how many Activities my project will contain, so if is there other way to do it I'm glad to hear other guesses.
EDIT
I'm trying the #Jared Rummler answer and maybe i'm doing something wrong... I've created a simple Json and I put on my Assets I parse the Json and I put it on a GlobalConstant then I made a "simple app".
First of all I have a TextView and a Button which contains the "your_special_color", and the return of it I put the GlobalConstant int as follows :
case "your_special_color":
return GlobalConstant.color;
Then what I tried is my first Activity has 1 TextView and 1 Button as I said before and they have the color "your_special_color" that I don't want to change it, BUT I have an Intent on my Button to open the other Activity that contains the same but with the GlobalConstant.color and it doesn't change.
I tried it doing this (my second Activity):
public class Main2Activity extends AppCompatActivity {
private Res res;
#Override public Resources getResources() {
if (res == null) {
res = new Res(super.getResources());
}
return res;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
Did I miss something?
Oh.. I figured it out I guess is doing this on my MainActivity2 ?
Button btn = (Button)findViewById(R.id.button2);
btn.setBackgroundColor(res.getColor(R.color.your_special_color));
You can create a class which extends Resources and override the methods getColor(int) and getColor(int, Theme).
Example:
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="your_special_color">#FF0099CC</color>
</resources>
Res.java
public class Res extends Resources {
public Res(Resources original) {
super(original.getAssets(), original.getDisplayMetrics(), original.getConfiguration());
}
#Override public int getColor(int id) throws NotFoundException {
return getColor(id, null);
}
#Override public int getColor(int id, Theme theme) throws NotFoundException {
switch (getResourceEntryName(id)) {
case "your_special_color":
// You can change the return value to an instance field that loads from SharedPreferences.
return Color.RED; // used as an example. Change as needed.
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return super.getColor(id, theme);
}
return super.getColor(id);
}
}
}
BaseActivity.java
public class BaseActivity extends AppCompatActivity {
...
private Res res;
#Override public Resources getResources() {
if (res == null) {
res = new Res(super.getResources());
}
return res;
}
...
}
This is the approach I have used in one of my apps, Root Check. If you override getResources in your activities and main application class you can change the theme programmatically (even though themes are immutable). If you want, download the app and see how you can set the primary, accent, and background colors from preferences.
If you take a look at the Accessing Resources document, what it says is that ...
Once you provide a resource in your application, you can apply it by referencing its resource ID. All resource IDs are defined in your project's R class, which the aapt tool automatically generates.
Furthermore,
When your application is compiled, aapt generates the R class,
which contains resource IDs for all the resources in your res/
directory. For each type of resource, there is an R subclass (for
example, R.drawable for all drawable resources), and for each
resource of that type, there is a static integer (for example,
R.drawable.icon). This integer is the resource ID that you can use
to retrieve your resource.
What this is saying, essentially, is that pretty much everything held as a resource in the res/ directory is compiled and referenced as an unchangeable constant. It is for this reason that the values of resource elements cannot be changed programmatically/at runtime, because they are compiled. As opposed to local/global variables & SharedPreferences, resource elements are represented in program memory as fixed, unchangeable objects. They are held in a special read-only region of program memory. In this regard, see also Changing value of R.String Programmatically.
What you can do is, to avoid using the same code at a thousand places in your project, create a common function that changes the value of the color in the SharedPreferences and use this method everywhere. I'm sure you knew this already, of course.
To reduce the amount of code you need to add to the project, there is an alternative. I have previously used the calligraphy library which allowed me to fix the font style & color throughout the app. This may be of some good use to you, check it out ...
R class is not supposed to be edited. It merely contains references to your resources.
You will need to set it manually. However, to reduce the burden of setting it manually you can try to use special libraries for preference saving, for instance:
Saber - https://github.com/jug6ernaut/saber
PreferenceBinder - https://github.com/denley/preferencebinder
(full list of similar libraries https://android-arsenal.com/tag/75)
Also, you might want to think about another way of applying styles and passing parameters - consider you would want to add some other parameters like height, width etc. For that purpose, you can define custom attribute in themes.xml/styles.xml:
<attr name="demoColor" format="reference|color" />
then define styles:
<style name="BaseActivity">
</style>
<style name="GreenActivity" parent="#style/BaseActivity">
<item name="demoColor">#00cd00</item>
</style>
<style name="RedActivity" parent="#style/BaseActivity">
<item name="demoColor">#ff0000</item>
</style>
then use that color in your xml like this:
... android:background="?demoColor" ...
and switch between GreenActivity and RedActivity styles in Activity.onCreate:
setTheme(isGreenStyle() ? R.style.GreenActivity : R.style.RedActivity)
setContentView(...)
With the above approach, you will be able to easily configure your styles in xml and it should be less code and easier to refactor in future. (You will still need to have one variable in preference to save whether you have green or red style)
Another way, if you want to show demos of your app with different colors is to use build variants / flavors for loading your app with different colors and styles (it is for build time - not runtime):
app/src/main/res/colors.xml
<resources>
<color name="demoColor">#00cd00</color>
</resources>
app/src/buildVariant/res/colors.xml
<resources>
<color name="demoColor">#ff0000</color>
</resources>
Now you can quickly switch between "main" and "buildVariant" in Build Variants menu and launch your app with different "demo" colors. The same way you can customize a lot of other attributes.
Search for "Build Variants" here http://developer.android.com/tools/building/configuring-gradle.html
You can't change an app's resources, they are all constants. Instead you can save your color in SharedPrefences and use the color from there.
See How to use SharedPreferences in Android to store, fetch and edit values.
If your app already has a R.color.green defined and you just want to access it based on what API returned you use:
int resourceID = getResources().getIdentifier("green", "color", getPackageName());
store hex color codes into sharedpreferences and then use parsecolor function store your all hexcodes of colors into sessions as a string and whenever you want to change color of perticular button ,textview..just retrive that color code from session and use it as
for ex.
session.setString("white","#FFFFFF");
String colorname=session.getString("white");yourtextview.setBackgroundColor(Color.parseColor(colorname);
I'm implementing internationalization for my application. The main part of the internationalization is supporting multi-languages.
One approach for supporting multi-language is, creating multiple values directories under the res/ directory and having strings.xml for the corresponding languages. Example here.
But my requirement is something like this:
The user enters his credentials to login to the application. Based on the language selected while creating an account on this app, the user would have selected a language.
So, on successful login, i'll be making a call to a service that will be returning all the strings in the application. And dynamically i must be associating these string to the labels in the application.
How can the above thing be done efficiently?
One approach that i have thought is, make a call to the service on successful login and store all the information on the Shared Preferences. and then use it.
Is there any other way to do this?
How do i change the text in cases of the xml layout files having android:text=""?
Please share your views regarding the same.
Take a look at Change language programmatically in Android . Whatever you do, you should use Android standard way (resources) instead of reinventing the wheel.
Update:
Due to your strange constraints, if you decide to reinvent the wheel, you could for example create derived classes using the TAG field of the views, something like:
public class LocalizableTextView extends TextView {
public LocalizableTextView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
setText(MyLocalizableStuff.get(this.getTag());
}
}
and create a static helper class MyLocalizableStuff like this: (needs error checking, etc, just typed out of my head)
public static class MyLocalizableStuff {
private static HashMap<Integer,String> sStringTable=new HashMap<>();
public static String get(Object code) {
Integer intCode=Integer.valueOf((String)code);
String result=sStringTable.get(intCode);
return result;
}
public static void init(Context ctx) {
// read your strings and store them on the stringtable
// you will call this init from onCreate like
// MyLocalizableStuff.init(context)
}
}
This way, you can insert LocalizableTextViews in your XML and assign a (numeric) TAG code that will map to the String and in construction time, will be assigned to the TextView. You could also use Strings as the code, but bear in mind that the HashMap will then be slower.
You could also use a SparseArray to store the string table instead of a HashMap, it will be probably faster.
But again, I wouldn't go this route.
On subclasses of View there is a getTag() method, which returns the android:tag attribute's value from .xml.
I would like the same for a MenuItem... is it okay to just cast it to a View?
Because item elements also allow a tag attribute in .xml...
Update: My goal with this is setting a tag in .xml, i.e. "notranslate", and querying it at runtime (we localize by hand at runtime, don't ask...)
It is always alright to cast, however, casting any Interface cannot be checked at compile time, only runtime. This is normally the reason many do not recommend casting an Interface that you have no control over. Having the proper error checking code is the best way to insure that such a cast does not break your code.
For the casting, it doesn't really matter whether the MenuItem is an Interface or a View, but the object it references must be one of View's subclasses, if not a View itself. If you are going to cast it, try the cast and catch a ClassCastException just in case as this is the error that will be thrown in runtime.
Another option is that since the MenuItem is simply an interface, you can easily just create a View subclass that utilizes MenuItem allowing you to do the cast. If you are doing a custom ContextMenu as many launchers do, then chances are your answer is nearly complete.
Hope this helps,
FuzzicalLogic
MenuItem is an interface. Any class can implement this interface and so it will not always be safe to cast the MenuItem to a View. You can use the "instanceOf" operator to test to see if the object that implements the MenuItem interface is indeed a View or not.
I understand that you want to define a flag in the XML definition of the menu and then at run time interrogate that flag to make a programmatic decision.
The Menu Resource Documentation records what attributes can be set in the XML. You can consider using (abusing) one of those settings such as the "android:alphabeticShortcut" to encode the flag and use the MenuItem::getAlphabeticShortcut() method to get the value. This does not require casting - it just uses the existing fields in the MenuItem XML construct/class for your own purposes.
Perhaps a less hacky way to do this is to keep a simple table in a separate assets file that lists the menu item identifiers and the special behavior associated with that identifier such as to translate or not to translate.
Alternatively create a simple class that has a table with this configuration information hard coded using the logical "#[+][package:]id/resource_name" resource identifier as the keys to the table. While this doesn't keep it all in one place (in the XML) it does it in a manner that is not encoding information in unused attributes, or relying on the ids not changing. The "table" could be implemented as a static method with an embedded switch statement allowing code such as "if (TranslationTable.shouldTranslate(menuItem.getItemId())) { do translation }"
I had a similar problem in that I wanted to associate some arbitrary data with each menu item so that I could handle menu items in a generic way without having to use hardcoded checks for individual item ids in code.
What I did was for a particular menu item (e.g. #+id/foo) There was an a TypedArray that was defined using the same name as the menu item ID. You could do this with other types of resources as well.
So to do the association, you get the resouce entry name (foo in my example) and then use that to look up the id of the other resource of a different type (#array/foo in my example).
In my handler for menu I had code like this:
Resources resources = getResources();
String name = resources.getResourceEntryName(item.getItemId());
int id = resources.getIdentifier(name, "array", "com.example");
if(id != 0)
{
TypedArray data = resources.obtainTypedArray(id);
// Use the typed array to get associated data
}
EDIT:
Actually it is even easier than that. There is nothing special about the ids on menu items other than you don't want multiple menu items with the same id. The id does not have to be of the form #+id/foo. It can actually also refer to other resources. So in my example above, instead of having the menu have an id of #+id/foo and using the resource manager to use that to find #array/foo, I changed to actually have the menu item have the id of #array/foo.
Now in my onOptionsItemSelected I have this:
Resources resources = getResources();
if("array".equals(resources.getResourceTypeName(item.getItemId())))
{
TypedArray data = resources.obtainTypedArray(item.getItemId());
// Use the typed array
}