Archive for February, 2010

quicktip: Working with strings.xml in Android and little bit about @

Very simple so straight to the point.

BAD:

In your xmls
- <Button android:id="@+id/buy_button" android:text="Buy Me" />

In your java code
- myButton.setText("Second Button");

GOOD:

Define your strings in strings.xml (You can name it anything) and place it in ‘res/values’ folder


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="buy_button">Buy</string>
</resources>

and then


- <Button android:id="@+id/buy_button" android:text="@string/buy_button" />
- myButton.setText(this.getString(R.string.buy_button));

Syntax for using a ‘resource’ in a xml or code is :
package.R.resource_type.resource_name
and
@[package:]resource_type/resource_name

NOTE: package here does not mean ‘java package’ but package == application, so if you are accessing a resource which is defined in your own app you can skip it. Thats why we use @strings/name or directly R.strings.name. Similarly to use resources defined by android we will use @android:string/name or android.R.string.name

For converting R.string.id to String you can either use getString(int) or getString(int, Object…) for adding dynamic values.


quicktip: How to convert a view to an image (android)

This is a quick tip to convert or draw your view on a canvas so that you can either show it as preview or use it for any drag – drop kind of operation. Very simple and self explanatory so just posting the code


View viewToBeConverted;

Bitmap viewBitmap = Bitmap.createBitmap(viewToBeConverted.getWidth(), viewToBeConverted.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);

viewToBeConverted.draw(canvas);

Thats it, now you can use ‘viewBitmap’ as a normal image. You can change a few parameters to create different kinds of image, for eg when you drag your app icon on bring it on the trash can to drop it becomes red etc


© Copyright 2009 TechJini Solutions Private Limited. All Rights Reserved
iDream theme by Templates Next | Powered by WordPress