Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Passing parameters into Activity from AndroidManifest.xml

Does anyone know if it's possible to pass parameters into an Activity from the AndroidManifest.xml file? I want to use the same activity in a couple of apps, but have a way of conditioning the appearance of that activity based on the app.

E.g. I'd like to write something like (in AndroidManifest.xml)

<activity android:name=".MyActivity"
              android:label="@string/app_name"
              android:screenOrientation="portrait">

        <extradata>
              <item name="foo" value="bar"/>
        </extradata>
</activity>

.. and be able to read out the value of bar in the onCreate of the activity. Is this something that can be done with the data attribute in an intent filter?

Thanks,

like image 583
Ben Clayton Avatar asked Feb 28 '11 17:02

Ben Clayton


2 Answers

Actually, there is way to do just that. Check this article :

http://blog.iangclifton.com/2010/10/08/using-meta-data-in-an-androidmanifest/

In short you can get the content of the tag using this :

ApplicationInfo ai = getPackageManager().getApplicationInfo(activity.getPackageName(),     PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
String myApiKey = bundle.getString("my_api_key");

Metadata tag is defined as this :

<meta-data android:name="my_api_key" android:value="mykey123" />

It is possible to access data in values, but if you want to specify something that is related to the activity, this is much cleaner approach.

Hope it helps.

like image 68
Pavel Lahoda Avatar answered Sep 29 '22 21:09

Pavel Lahoda


Use res/values/strings.xml

Save your data here. Use somethings like

<string-array name = "foo">
<item>bar1</item>
<item>bar2</item>
<item>red</item>
<item>blue</item>
<item>one</item>
<item>two</item>
</string-array>

you can then get this by using

Resources r;

r = getResources():

String[] foos = r.getStringArray(R.array.foo);

I think this is what your looking for. But if your looking to stylize your app then you should look at using a theme.

[android example for themes][1]

[1]: http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html"THEME EXAMPLE"

like image 22
Wayner Avatar answered Sep 29 '22 21:09

Wayner