Pages

Showing posts with label simple example. Show all posts
Showing posts with label simple example. Show all posts

Thursday, 30 June 2011

View visibility

How do I hide and show view controls in my app?
View controls (TextView, EditText, Button, Image, etc) all have a visibility property. This can be set to one of three values:
  • Visible - Displayed
  • Invisible - Hidden but space reserved
  • Gone - Hidden completely
The visibility can be defined in the layout XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
     android:id="@+id/button1"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You can see me"
    android:visibility="visible" />
    <Button
     android:id="@+id/button2" android:dr
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You cannot see me, but you can see where I am"
    android:visibility="invisible" />
    <Button
     android:id="@+id/button3"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="You have no idea that I am here"
    android:visibility="gone" />
</LinearLayout>

For the LinearLayout above, the three buttons laid out horizontally with equal weights will be displayed as below. You can see the first, the space for the second, but not the third:



To set the visibility in code use the public constant available in the static View class:

Button button1 = (TextView)findViewById(R.id.button1);
button1.setVisibility(View.Visible);

You see?

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.

Wednesday, 15 June 2011

First Steps: Returning values from an Activity

How do I return  a value from an Activity?
Below is some simple example code for creating a new Intent to launch an Activity named Activity1. Here we use the startActivityForResult method which takes the intent and an identifier (an arbitrary integer):

Activity1.java:
final static int REQUEST_CODE = 1234;

private void startActivity() {
  Intent myIntent = new Intent(getBaseContext(), Activity2.class);
  myIntent.setAction(Intent.ACTION_VIEW);
  startActivityForResult(myIntent, REQUEST_CODE);
}

In your second activity you should use the following code to return a result value and terminate the activity:

Activity2.java:
...
  setResult(1);
  finish();
...

Returning to your first activity and override the activity's onActivityResult method as below. Check the result code to determine the result is coming from the expected source then you can read resultCode and change logic depending upon its value:

Activity1.java:

...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(requestCode == REQUEST_CODE) {
    // Do something with resultCode
  }
}
...

It is worth noting that you can not open activities (or dialogs for that matter) in a modal fashion, in fact nothing is modal in android as that would lock the UI which is not permitted. Listeners are always used to receive the results.

Tuesday, 14 June 2011

First Steps - Passing values to an Activity

How do I pass a value to an activity?

To start an Activity you use an Intent. In this intent you can pass data which is returned as a Bundle object.

Android Activities and Intents

Below is some simple example code for creating a new intent to launch an Activity named MyActivity. Note the call to the putExtra method which accepts a key name ("content") and a value:

Intent myIntent = new Intent();
String packageName = this.getPackageName();
myIntent.setClassName(packageName,
packageName + "." + MyActivity.class.getSimpleName());
myIntent.putExtra("content", "my content string");
startActivity(myIntent);

Here is the code for the called activity with the Bundle data extracted from the intent. You can then retrieve the passed extra content from the bundle object:

public class MyActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contentweb);

    Bundle bundle = getIntent().getExtras();
    String content = bundle.getString("content");
  }
}

All pretty simple when you know how.

Thursday, 9 June 2011

Creating an Android Preferences Screen

How do I add a preferences / setting screen to my android app?
Thankfully it is very easy to create a preferences screen, much like those you'd find within the Settings on your handset. A preference screen requires a special XML definition, you cannot use standard layouts and views, however this can still be placed within your layout folder.

The PreferenceScreen layout can be separated into sections with a PreferenceCategory which has a title and is displayed as a dividing bar o the screen. There are several preference type views:

EditTextPreference - text box entry (text string)
CheckBoxPreference - tickable check box (true/false boolean)
ListPreference - Selection from array of options (text string)
RingtonePreference - Selection of Uri of ring tones stored on device

A simple example of a preferences screen layout is shown below:

/res/layout/prefs.xml
Preferences screen
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="Preferences">

  <PreferenceCategory
     android:title="Options">

     <CheckBoxPreference
       android:key="pref_opt1"
       android:title="Option 1"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
    <CheckBoxPreference
       android:key="pref_opt2"
       android:title="Option 2"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
  </PreferenceCategory>

  <PreferenceCategory
     android:title="Selection">
      
    <ListPreference
        android:key="pref_type"
        android:title="Type"
        android:summary="Select item from array"
        android:entries="@array/types"
        android:entryValues="@array/types_values"
        android:defaultValue="1"
        />

    <EditTextPreference
        android:key="pref_text"
        android:title="Input text"
        android:summary="Tap to enter some text"
        android:dialogTitle="Enter text"
    />
     
  </PreferenceCategory>

  <Preference
    android:title="Intent"
    android:summary="Open a webpage">

    <intent
      android:action="android.intent.action.VIEW"
      android:data="http://android-elements.blogspot.com/" />

  </Preference>
   
</PreferenceScreen>

The ListPreference in the XML above references two arrays; one for the option text and one for the option values. These should be defined in your strings resource file:

/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="types">
     <item>Type 1</item>
     <item>Type 2</item>
     <item>Type 3</item>
    </string-array>
    <string-array name="types_values">
     <item>1</item>
     <item>2</item>
     <item>3</item>
    </string-array>
</resources>

Your activity must extend the PreferenceActivity rather than a standard activity. This should be defined as below:


src/your.package.name/Prefs.java
package com.example.com;

import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.prefs);
    }   
}

Don't forget to add this activity to your manifest!
You can read and write the prefence values in code with the following method examples...

// String
    public static String Read(Context context, final String key) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getString(key, "");
    }
 
    public static void Write(Context context, final String key, final String value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putString(key, value);
          editor.commit();        
    }
     
    // Boolean  
    public static boolean ReadBoolean(Context context, final String key, final boolean defaultValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(key, defaultValue);
    }
 
    public static void WriteBoolean(Context context, final String key, final boolean value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putBoolean(key, value);
          editor.commit();        
    }

Just as an aside, many apps I have build have been based upon a white theme rather than the default android dark. It is easy to set your preferences screen to use the built in Light theme so that it looks more consistent within your app, simply set the theme for the activity within your manifest as follows:

<activity android:name=".Prefs" android:theme="@android:style/Theme.Light">

Then your preferences screen will look something like this:

Preferences Screen (Light theme)

Please see my post on Introducing Themes for more information about themes and styles.

Monday, 6 June 2011

Customizing the Title Bar

How do I change the title bar for my app?
Often I find that I want to remove the Android title bar from my app entirely and create my own within the layouts. To achieve this, just set the theme for the entire application, or individual activity to Theme.NoTitleBar then set my own title bar within the layouts as required:

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  android:theme="@android:style/Theme.NoTitleBar"
  <activity android:name=".Main" android:theme="@android:style/Theme.NoTitleBar" />

However, the standard title bar is fairly flexible in terms of background and text options (although centering the title text is not trivial). To modify it we start off by creating our own theme and, in this case, inherit from the default android theme. This theme contains system names for the android title styles and effectively overrides them. Where the name denotes a style, e.g. windowTitleStyle, a reference to a defined style is required.

/res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.myTheme.TitleBar" parent="android:Theme">
    <item name="android:windowTitleBackgroundStyle">@style/windowTitleBackgroundStyle</item>
    <item name="android:windowTitleStyle">@style/windowTitleStyle</item>
    <item name="android:windowTitleSize">50dip</item>
  </style>
</resources>

/res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="windowTitleBackgroundStyle">  
    <item name="android:background">@FF000</item>                
  </style>
  <style name="windowTitleStyle">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:padding">12dip</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">16sp</item>
  </style>
</resources>

Finally set the theme within the manifest for either the application or individual activities...

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  android:theme="@style/Theme.myTheme.TitleBar" >

Thursday, 26 May 2011

First Steps - Introducing Themes

How do I use themes in my app?
This post extends my previous post introducing styles, so if you've not used styles in android before I would recommend reading that first.

A theme is specified for an entire application or individual activities within the manifest. It encapsulates a number of visual style settings, such as text and button styling.

Android has a default theme which is the 'dark' theme, black background with white text, that you will see it you were to open the Settings menu for example. When you create an android app you do not need to specify the theme as the dark theme is used by default.

It is likely that you will at some point want to hide the application title bar, this can be done by setting the theme to Theme.NoTitleBar. Android also has a 'light' theme built in (black on white) which can be used by setting the theme to Theme.Light. You can also chain the theme settings to allow combinations, for example Theme.Light.NoTitleBar. Themes are applied in the manifest as shown below:

Manifest sample:
<application
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name"
  android:theme="@android:style/Theme.Light">
  <activity
    android:name=".Main"
    android:theme="@android:style/Theme.Light.NoTitleBar">

System styles are prefixed for the @android tag. Much like styles, custom themes are defined within an XML file within your resources and each theme must have a name and can optionally have a parent, for inheriting properties:

res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.myTheme" parent="android:Theme.Light.NoTitleBar">
     <item name="textSize">20sp</item>
    </style>
</resources>

You can then apply your own theme within your project manifest, as shown below.

Manfiest sample:
...
<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/Theme.myTheme">
    ...

Wednesday, 25 May 2011

First Steps - An introduction to Styles

How do I use styles in my app?
Use of styles allows you to define reusable visual settings to help maintain a consistent look-and-feel to your app.
The simple example below shows how to create a style for titles, which will be larger text, and warnings which will be red. Each style must have a name and can then list multiple properties:

values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="myTitle">
      <item name="android:textSize">16sp</item>
    </style>
    <style name="myWarning" parent="@style/myTitle">
      <item name="android:textStyle">bold</item>
      <item name="android:textColor">@colors/myRed</item>
    </style>
</resources>

A few things to note here, firstly that you can put any styling name into the item tag that you would use within your layout definitions. Also note that myWarnings has its parent set as myTitle and so inherits the 16sp text size defined there. Finally, the textColor value could be a standard hex colour (i.e. #FF0000) but it is good practice to put colours into a separate resource so that one you only need to update one location if you want to change it:

values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="myRed">#FF0000</color>
</resources>

Now it is simply the case of applying the style within your layouts:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="My styled text view"
        style="@styles/myWarning" />
</LinearLayout>

Note that the style attribute is not prefixed by the android tag.

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

Sunday, 22 May 2011

Defining a custom button with background and textcolor styles

How do I define a custom button with background and text color styles?

This is a simple guide to styling buttons within your Android app. We start of with a button in your Layout, and set the style to a custom style name:

<Button
  android:id="@+id/myButton"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Tap me!"
  style="@style/button" />

It is a good idea to use a style rather than set the background directly as it allows you to set the text properties as well as background graphic options. It also makes it very easy to re-use your style.

res/values/styles.xml
<style name="button">
  <item name="android:background">@drawable/button</item>
  <item name="android:textColor">#FFF</item>
  <item name="android:textSize">16sp</item>
  <item name="android:gravity">center_vertical|center_horizontal</item>
</style>

The background of a Button is expected to be a Drawable (image), but we are able to define this as a shape with an item for each state (pressed, focussed or default). To keep this simple we'll stick to simple colour changes:

res/drawable/button.xml
<?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true" >
    <shape>
      <solid android:color="#FF0000" />
    </shape>
  </item>

  <item android:state_focused="true" >
    <shape>
      <solid android:color="#DDDDDD" />
    </shape>
  </item>

  <item>
    <shape>
      <solid android:color="#FFFFFF" />
    </shape>
  </item>

</selector>

You may want to produce more fancy buttons, in which case you will need to use more shape options (such as rounding and strokes) or produce a Drawable image for each state. If you want to use images, these should be 9-Patch PNGs that allow Android to stretch the image to fit any content. I will cover these another day!

Thursday, 19 May 2011

Advanced Lists: Using class object within ListView

How do I build a ListView to display my custom class items?

One of the most common interface elements used in Android apps is the ListView. This presents to the user a scrollable list of tappable items. The best place to start with this is and Android Developers ListView Tutorial which will cover the basics of creating an activity with the ListView control and displaying a list of items from a string array.

In a real world app you will probably want to build a list with something other than a string array. Commonly you will have a collection of your own type of object, or you may want to display listview items with an icon. I will show you how to use a ListView to display these objects and also handle the tap event.

Let's start with the class object that will consist of a text label, a drawable for the icon and also an index value to track item selection:

CustomListItem.java
package com.example.advancedList; import android.graphics.drawable.Drawable; public class CustomListItem { private int mIndex; private String mLabel; private Drawable mPicture; public CustomListItem(final int index, final String label, final Drawable pic) { mIndex = index; mLabel = label; mPicture = pic; } public int getIndex() { return mIndex; } public String getLabel() { return mLabel; } public Drawable getPicture() { return mPicture; } }
Now that we have our class defined, let's create the layout that will be used to display the individual list item, which is a simple RelativeView with an ImageView for the icon and a TextView for the label:

Create res/layout/list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  
   <TextView
       android:id="@+id/txtLabel"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" 
       android:text="List item" />
   <ImageView
       android:id="@+id/txtImgIcon"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" 
       android:src="@null"
       android:layout_toRightOf="@id/txtLabel" />
  
</RelativeLayout>

Hopefully so far everything has been quite straight forward. We now need to define a custom list adapter that extends the BaseAdapter class, this will allow us to fully control the way the ListView is constructed.

Create a class named MyListItemAdapter.java:
package com.example.advancedList;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

// Custom list item class for menu items
public class MyListItemAdapter extends BaseAdapter {

    private List<CustomListItem> items;
    private Context context;
    private int numItems = 0;

    public MyListItemAdapter(final List<CustomListItem> items, Context context) {
        this.items = items;
        this.context = context;
        this.numItems = items.size();
    }
 
    public int getCount() {
        return numItems;
    }

    public CustomListItem getItem(int position) {
        return items.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
       
        // Get the current list item
        final CustomListItem item = items.get(position);
        // Get the layout for the list item
        final RelativeLayout itemLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        // Set the icon as defined in our list item
        ImageView imgIcon = (ImageView) itemLayout.findViewById(R.id.imgIcon);
        imgIcon.setImageDrawable(item.getPicture());
     
        // Set the text label as defined in our list item
        TextView txtLabel = (TextView) itemLayout.findViewById(R.id.txtLabel);
        txtLabel.setText(item.getLabel());

        return itemLayout;
    }
 
}

Next let's knock together a simple layout for the main activity. This will consist of a ListView for our items and a TextView that is displayed if the list is ever empty. Note here the use of special Android reserved IDs for the controls. This allows the list to be picked up for the ListActivity we'll use and also know to only display the TextView if there is no data in the ListView.

We'll call the file res/layout/list_example.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">

    <ListView
      android:id="@id/android:list"
      android:layout_height="wrap_content"
      android:layout_width="fill_parent" />
     
   <TextView
      android:id="@id/android:empty"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Nothing to list" />
</LinearLayout>

We now need to build our main Activity which extends the ListActivity class using our layout defined previously. Within the activity's onCreate method we create a List of our CustomListItem type and add 3 new items to it. We then populate a new ListAdapter using our myListItemAdapter class and assign to it our list of items:

src/com.example.advancedList/Main.java :
package com.example.advancedList;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Main extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_example);
        
// Create list of items based upon class
        final List<CustomListItem> items = new ArrayList<CustomListItem>(3);
     
        items.add(new CustomListItem (1, "Item 1", getResources().getDrawable(R.drawable.icon)));
        items.add(new CustomListItem (2, "Item 2", getResources().getDrawable(R.drawable.icon)));
        items.add(new CustomListItem (3, "Item 3", getResources().getDrawable(R.drawable.icon)));
     
        // Populate the list view
        ListAdapter adapter = new myListItemAdapter(items, this);
        ListView lv = getListView();  // Because we are extending ListActivity we cal  this but could specify
        lv.setAdapter(adapter);
        lv.setTextFilterEnabled(true);
     
        // Add listener for item clicks
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
             
                  // Retrieve our class object and use index to resolve item tapped
                    final MenuListItem item = items.get(position);
                    final int menuIndex = item.getIndex();
                    switch (menuIndex) {
                    case 1:                      
                        break;
                    case 2:                      
                        break;
                    case 3:
                        break;
                    default:
                        break;
                    }
            }
        });      
    }
 
}

You'll see that once we have our list adapter set up it is applied to the list view. We then assign a listener to the list view to pick up click events. Within this the first thing we do it obtain the item from the list that was clicked. We then have the freedom to make our code react to any aspect of our object.

I have used this approach several times and in fact have never displayed a list from a string array. I hope you find this guide useful.


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.

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.