Dynamic Resource Loading Android - android

I'm trying to find a way to open resources whose name is determined at runtime only.
More specifically, I want to have a XML that references a bunch of other XML files in the application apk. For the purpose of explaining, let's say the main XML is main.xml and the other XML are file1.xml, file2.xml and fileX.xml. What I want is to read main.xml, extract the name of the XML I want (fileX.xml), for example, and then read fileX.xml. The problem I face is that what I extract form main.xml is a string and I can't find a way to change that to R.raw.nameOfTheFile.
Anybody has an idea?
I don't want to:
regroup everything in one huge XML file
hardcode main.xml in a huge switch case that links a number/string to the resource ID

I haven't used it with raw files or xml layout files, but for drawables I use this:
getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www");
to get the identifier (R.id) of the resource. You would need to replace drawable with something else, maybe raw or layout (untested).

I wrote this handy little helper method to encapsulate this:
public static String getResourceString(String name, Context context) {
int nameResourceID = context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName);
if (nameResourceID == 0) {
throw new IllegalArgumentException("No resource string found with name " + name);
} else {
return context.getString(nameResourceID);
}
}

There is another method:
int drawableId = R.drawable.class.getField("file1").getInt(null);
According to this blog it's 5x times faster than using getIdentifier.

Related

Change values inside an xml file at runtime [duplicate]

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);

Get language translation in xml from external json file

As a part of an app that I am developing there is request that it has to download JSON file that contains language translation that needs to be used in app instead of strings.xml file that is commonly used because this way any translation in app can be changed by updating external JSON file on some web portal and it avoid the need to make new build every time you want to change language translation.
I've already done this, and everything is working fine in a following way:
For example If I have button in xml once the activity starts I can reference the button and set the it's text from JSON that I've downloaded at the startup.
btnLogin = (Button) v.findViewById(R.id.btnLogin);
// reads translation from json that is stored in external application directory
btnLogin.setText(ResourceManager.getString("btnLogin"));
But my question is is there any way that I can avoid setting this text always from activity, can I somehow do it from XML file where this button is defined?
<Button
android:id="#+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="{ResourceManager.getString("btnLogin")}"/>
Is there any possibility that let's me call some function from xml and bind it's result to text attribute or is there any other way which avoids referencing all buttons/textviews and other controls from activity and setting text from there?
Have you tried overriding getResources() in you Application class and then
returning an extended version of Resources.
Ok, I tried this and it seemed to work for most of the resources in my xml file.
You may have to override this in more than one place. I just overrode it inside my Application class.
private MyResources resources;
#Override
public Resources getResources() {
if (resources == null) {
resources = new MyResources(super.getResources());
}
return resources;
}
class MyResources extends Resources {
public MyResources(Resources resource) {
super(resource.getAssets(), resource.getDisplayMetrics(), resource.getConfiguration());
}
public String getString(int resId) {
return "Bob"; // Use your ResourceManger here
}
}
This worked for me..

Theme Dependent Android Strings

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.

Is there a way to set setContentView(int id) dynamically?

I'd like to be able to loop through a list of xml layout files instead of having to specify a particular one in the setContentView argument.
Obviously the types are incorrect, but something like:
ArrayList<String> pages = new ArrayList<String>();
//(Where each of the xml pages are stored like R.layout.page1, R.layout.page2, etc)
setContentView(pages.get(0));
Is this possible somehow?
You should use the ViewFlipper widget instead. Here is an example.
It is cleaner to manage the content views and their children widgets this way.
Anyway, the resource IDs can be obtained from names using the Resources.getIdentifier method.
Yes. it's possible. But two notes:
The ids are ints, not Strings.
You need to manage the views inside them properly.
In an application I have created I use the following code to set the image button to a particular resource:
imgBtnCard.setImageResource(this.getResources()
.getIdentifier("com.twp.cptshitface:drawable/" +
cardType + cardDetails[1] , null, null));
I would say that this is what you are looking for:
int resLayoutId = this.getResources().
getIdentifier("your.package.namespace:layout/" +
pages.get(0), null, null);
setContentView(resLayoutId);
// where pages.get(0) returns a string such as "main2"
I've quickly tested this code in the onCreateMethod.
remember to clean your project if you add more layouts and/or resources so the id's are updated!

MenuItem#getTag()

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
}

Categories

Resources