Pages

Showing posts with label quick tip. Show all posts
Showing posts with label quick tip. Show all posts

Wednesday, 29 June 2011

Quick Tip: Copyright symbol in a string

Very quick tip; to display the copyright symbol in your app, you can use Unicode definition in a string, as shown below:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="\u00A9 Android Elements 2011" />


Displaying the copyright notice in an app

Wednesday, 22 June 2011

Opening call dialog

How do I make my app call a phone number?
The easiest method is to create an intent which opens the device caller dialog. Because this is not actually initiating the call, no additional permissions are required by your app.

final String phoneNumber = "01234 123456";
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));

Android dialler intent


Monday, 20 June 2011

How to close soft keyboard on button press

How can my app hide the soft keyboard when a button is pressed?
A simple example of this requirement would be a search box within your app. This would be defined in your layout markup as a EditText view and a Button view. Once the user has entered some text, they will typically click on the search button. Default behaviour is that the soft keyboard is still visible until the user dismisses it. You can hide the keyboard using the following code, probably on the button click handler:

InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
EditText editText = (EditText)findViewById(R.id.editText);
inputMgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

The method requires a reference to the EditText view that was the source of the soft keyboard launch.

Monday, 13 June 2011

Cannot install Android Development Tools / DDMS

If you see the following error when updating you Android Development Tools and DDMS in Eclipse on a Windows PC, you need to run Eclipse as Administrator.

"The operaton cannot be completed. See the details."

"Cannot complete the install because of a conflicing dependency."

Cannot complete the install because of a conflicing dependency

Tuesday, 24 May 2011

Referencing a drawable in code

A very quick one here, but I often forget how to get a reference in code to my drawable resources, so here it is...

Drawable d = getResources().getDrawable(R.drawable.icon);

The getResources() method available depending upon context. If you need to reference it from within your own class then you'll need to pass a context in.

Monday, 23 May 2011

Displaying the Version number of your app

How do I display the versionName from my manifest file in my app?

The versionName value in your project manifest file is a 'friendly' version number that is displayed to the user on the market screen and in the application list. The versionCode value is the integer that allows you to version and publish updates to your app on the market (refer to the official documentation on Versioning Your Applications).

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidelements.myProject"
      android:versionCode="1"
      android:versionName="1.0.0">

You might want to display the version name in your app, on a splash or about screen perhaps. To do this you need to use the PackageInfo class, here's how...

Add the following imports:
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

Use the following code to display the value in a TextView:
String versionName = "";
try {
    final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    versionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
    e.printStackTrace();
}
TextView tv = (TextView) findViewById(R.id.tvVersion);
tv.setText(versionName);

Tuesday, 17 May 2011

Best Eclipse Shortcuts

There are many sites listing their top Eclipse shortcuts, but for what it's worth I would like to add my most used keyboard shortcuts since starting with Eclipse...

Ctrl + Shift + O = organise and import missing imports
Alt + Shift + R = refactor (rename variable or method)

Ctrl + 1 (one) = Quick fix popup
Ctrl + D = Delete line
Ctrl + O = Outline (easily navigate to parts of project)
Ctrl + M (or double-click tab) = Maximise source when coding
Ctrl + . = Jump next error or warning


Alt + UP / Alt + DOWN = Move selection up or down
Alt + LEFT / Alt + RIGHT = Jump to recently edited sections


Ctrl + Shift + R = open resource (start typing any file name - like indexed search)
Ctrl + Shift + F - Formats code to settings defined under Window > Preferences > Java > Code Style > Formatter

Monday, 16 May 2011

Setting a style on dynamically created view control

How do I set a TextView or Button style in code?
Styling within Android allows you to define a reusable look-and-feel, much like styles in CSS on a web page. These are very easy to assign in your XML layouts, however you cannot set the style of a View control programmatically. This is a pain if you are building a layout dynamically.

To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:

res/layout/tvtemplate.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template"
        style="@style/my_style" />

then inflate this to instantiate your new TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

You can then continue to work with your TextView as usual. There may be other workarounds for this, if you have any please feel free to comment. It's also possible that an Android API update will add a property for this in future.

Wednesday, 11 May 2011

Adding views to a layout dynamically

How do I add a button to my layout in code?

Firstly add the appropriate import to your Activity class for the view to add, in this case a button:

import android.widget.Button;

Then create a new button object within the activity onCreate method:

Button myButton = new Button(this);
myButton.setText("Tap Me");

Finally add the button to the layout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
layout.addView(myButton);

Obviously the same logic applies to other views (TextViews, etc).

You might also want to apply fonts to your controls, if so take a look at Using a True-Type Font in your Android app.

Friday, 6 May 2011

Using a True-Type Font in your Android app

Android supports true-type fonts, but these have to be set in code, you cannot specify the fonts in the layout XML.

Firstly copy the font file into your assets folder. I usually create a fonts sub-folder:

project/assets/fonts/myfont.ttf

Second, and finally, apply the font to a TextView in code:

TextView tv = (TextView)findViewById(R.id.TextView1);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
tv.setTypeface(face);

TextViews, Buttons, CheckedTextView and RadioButtons all have the setTypeface method, but as a note of warning, not all .ttf files will necessarily display in your Android app, if it fails your app will force close with the following error: RuntimeException: native typeface cannot be made.

Wednesday, 4 May 2011

How to Fix Screen Orientation

How do I stop my Android app rotating?

There are a number of reasons that you may want to prevent your screen from rotating. When an Android device is rotated, by default the currently running activity is restarted. This will often require you to code to maintain the state that the activity was in prior to rotation. Alternatively you may simply want to display only in landscape, perhaps for a game.

To fix your screen orientation, simply set the screenOrientation attribute of the activity within your project manifest, as shown below, to either portrait or landscape:

<activity
    android:name=".myActivity"
    android:screenOrientation="portrait">

You can also do the same thing in code:

myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Please refer to the official documentation for more details.

Thursday, 21 April 2011

Adding a Menu to your Android app

Adding an Android Menu to your app that opens when the hardware menu button is pressed

This is very simple so we'll jump straight into the XML file that defines the menu. Typically menu XML definitions will be kept in a menu folder within the resources folder; res. Create the directory if it is missing and add a new XML file called 'example.xml'.

The following full path should now exists within your project:

  res/menu/example.xml

Open the XML file and paste in XML below. Here we are defining a menu with a single item labelled "Refresh". This item has an icon, but this is not a requirement:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_refresh"
     android:icon="@drawable/ic_menu_refresh"
      android:title="Refresh" />
</menu>

Now open the activity class that you want to include the menu in. Add the following imports at the top of the class:

import android.view.Menu;
  import android.view.MenuInflater;
  import android.view MenuItem;

Two methods are required within your activity class, the first creates the menu options by inflating the xml definition we created:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.example, menu);
        return true;
    }
   
The second method handles the menu item selection. Here I use a case statement to react in response to the ID of the tapped menu item:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_refresh:
            // Refresh something
            return true; 
        default:
            return super.onOptionsItemSelected(item);
        }
    }

Now run your app and hit the menu button and you should see something like this...

Android app with menu

For more detail please refer to the Android Developer Creating Menus guide.

Monday, 18 April 2011

Quick Tip: Opening a URI in the web browser

Below is example code to open a web page URI / URL in the web browser:

  String webPageUri = "http://android-elements.blogspot.com/";
  Uri uri = Uri.parse(webPageUri);
  if (uri != null) {
    Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(myIntent);
  }

First we parse the uri string. If we have a non-null value we create a new Intent object set to use ACTION_VIEW with the uri as a parameter. ACTION_VIEW will perform the appropriate action for the contents of the provided uri. Then we call a method to start the new activity with this intent object.

Finally, we must ensure the app has internet access to call a web page (see my list of common Android pitfalls) so add the following permission to the manifest:

<uses-permission android:name="android.permission.INTERNET" />


Review the Android Developers site for more on intents and my Android Building Blocks guide for getting started.