tag:blogger.com,1999:blog-46129281255267549872024-03-06T04:34:20.292+00:00Android ElementsAndroid basics, tutorials, app reviews, news and moredanhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.comBlogger34125tag:blogger.com,1999:blog-4612928125526754987.post-12595294649026709112011-06-30T22:34:00.000+01:002011-06-30T22:34:56.137+01:00View visibility<b>How do I hide and show view controls in my app?</b><br />
View controls (TextView, EditText, Button, Image, etc) all have a <b>visibility </b>property. This can be set to one of three values:<br />
<ul><li><b>Visible </b>- Displayed</li>
<li><b>Invisible </b>- Hidden but space reserved</li>
<li><b>Gone </b>- Hidden completely</li>
</ul>The visibility can be defined in the layout XML:<br />
<br />
<pre><?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:<span class="Apple-style-span" style="background-color: #ffe599;">visibility="visible"</span> />
<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:<span class="Apple-style-span" style="background-color: #ffe599;">visibility="invisible"</span> />
<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:<span class="Apple-style-span" style="background-color: #ffe599;">visibility="gone"</span> />
</LinearLayout></pre><br />
For the <b>LinearLayout</b> above, the three buttons laid out horizontally with equal <b><i>weights</i></b> will be displayed as below. You can see the first, the space for the second, but not the third:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivG8j9Cs0JmNHAIH9AtcgmEEBOcaV9kTUXNQlK1txiOisAejdB6tiqx0C-rnf8jUrnUqSBbWBDu0SY67z94l_e1fKjD_YM3nIv9jGAm4vDH_zyAT37_rTZogKH_B6i-241VmTXi25Qys1J/s1600/android-elements-visibility.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivG8j9Cs0JmNHAIH9AtcgmEEBOcaV9kTUXNQlK1txiOisAejdB6tiqx0C-rnf8jUrnUqSBbWBDu0SY67z94l_e1fKjD_YM3nIv9jGAm4vDH_zyAT37_rTZogKH_B6i-241VmTXi25Qys1J/s1600/android-elements-visibility.png" /></a></div><br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">To set the visibility in code use the public constant available in the static <b>View </b>class:</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><pre style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">Button button1 = (TextView)findViewById(R.id.button1);
button1.setVisibility(View.Visible);</pre><br />
You see?danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-29138803641550552762011-06-29T23:30:00.000+01:002011-06-29T23:30:55.925+01:00Quick Tip: Copyright symbol in a stringVery quick tip; to display the copyright symbol in your app, you can use Unicode definition in a string, as shown below:<br />
<br />
<pre><TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="<span class="Apple-style-span" style="background-color: #ffd966;">\u00A9</span> Android Elements 2011" /></pre><br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR9cnTGafQAsBuIDlQwm9d6njeLR9xHhl6N2faxEs8led7rCiF_A_-sOKFDOsduTbZiwT4fqW4JUleg6invkZJRrKOsDJJ1W3SBryO7VcsWfAqVZzu7cLfn4IZ5e-FFnUX7TPleH2KwSBC/s1600/android-elements-copyright.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR9cnTGafQAsBuIDlQwm9d6njeLR9xHhl6N2faxEs8led7rCiF_A_-sOKFDOsduTbZiwT4fqW4JUleg6invkZJRrKOsDJJ1W3SBryO7VcsWfAqVZzu7cLfn4IZ5e-FFnUX7TPleH2KwSBC/s1600/android-elements-copyright.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Displaying the copyright notice in an app</td></tr>
</tbody></table>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-44786395285623334012011-06-22T22:03:00.000+01:002011-06-22T22:03:47.670+01:00Opening call dialog<b>How do I make my app call a phone number?</b><br />
The easiest method is to create an <b>intent </b>which opens the device caller dialog. Because this is not actually initiating the call, no additional <b>permissions </b>are required by your app.<br />
<br />
<pre>final String phoneNumber = "01234 123456";
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
</pre><br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigRmGnAVaL3UNtTwBDTPHb82GzxPUef0GR21jvUTBoHPl2h1Ji8BB532b5_Cl5OY07UiSFlTxpxHqWHZVlUdHg5okMx79XdQ6QmL8Ge3jIirRY1i9Bls-SOR1GjYGdijNbHU2N6PMtY5Zd/s1600/android-elements-dial.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigRmGnAVaL3UNtTwBDTPHb82GzxPUef0GR21jvUTBoHPl2h1Ji8BB532b5_Cl5OY07UiSFlTxpxHqWHZVlUdHg5okMx79XdQ6QmL8Ge3jIirRY1i9Bls-SOR1GjYGdijNbHU2N6PMtY5Zd/s320/android-elements-dial.png" width="212" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Android dialler intent</td></tr>
</tbody></table><br />
<br />
<span id="goog_627218000"></span><span id="goog_627218001"></span>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-19340163741684329522011-06-20T12:23:00.001+01:002011-06-20T12:29:39.257+01:00How to close soft keyboard on button press<b>How can my app hide the soft keyboard when a button is pressed?</b><br />
A simple example of this requirement would be a search box within your app. This would be defined in your layout markup as a <b>EditText </b>view and a <b>Button </b>view. Once the user has entered some text, they will typically click on the <i>search </i>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:<br />
<br />
<pre><span class="Apple-style-span">InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
EditText editText = (EditText)findViewById(R.id.editText);
</span>inputMgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);</pre><br />
The method requires a reference to the EditText view that was the source of the soft keyboard launch.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-49598903241025816812011-06-15T01:00:00.002+01:002011-12-31T16:00:12.493+00:00First Steps: Returning values from an Activity<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
<b>How do I return a value from an Activity?</b></div>
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
Below is some simple example code for creating a new <b>Intent</b> to launch an <b>Activity </b>named Activity1. Here we use the <span class="Apple-style-span" style="font-family: monospace; white-space: pre;">startActivityForResult </span>method which takes the intent and an identifier (an arbitrary integer):</div>
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
<br />
<b>Activity1.java:</b></div>
<pre>final static int <span class="Apple-style-span" style="color: #073763;">REQUEST_CODE</span> = 1234;
private void startActivity() {
Intent myIntent = new Intent(getBaseContext(), Activity2.class);
myIntent.setAction(Intent.ACTION_VIEW);
startActivityForResult(myIntent, <span class="Apple-style-span" style="color: #073763;">REQUEST_CODE</span>);
}</pre>
<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
In your second activity you should use the following code to return a result value and terminate the activity:<br />
<br />
<b>Activity2.java:</b></div>
<pre>...
setResult(1);
finish();
...</pre>
<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
Returning to your first activity and <b>override </b>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:<br />
<br />
<b>Activity1.java:</b><br />
<br />
<pre>...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == <span class="Apple-style-span" style="color: #073763;">REQUEST_CODE</span>) {
// Do something with resultCode
}
}
...</pre>
<br />
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.</div>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-90278776823303771732011-06-14T09:58:00.001+01:002011-06-15T11:20:36.638+01:00First Steps - Passing values to an Activity<b>How do I pass a value to an activity?</b><br />
<br />
To start an <b>Activity </b>you use an <b>Intent</b>. In this intent you can pass data which is returned as a Bundle object.<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdmCi-nkui45kZunYgMYOUmv9htteCoCb8VINqUJ_5Omz7lKS0ppzJ9IvPSIzKkna2jjTzF39hu0pcSp80qy4cDZpEFkgRsIWJh1OvUDbpopjFVqX9jftvMZKgYtv-X1FT91wNVIm4I232/s1600/android_elements_activities.gif" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="100" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdmCi-nkui45kZunYgMYOUmv9htteCoCb8VINqUJ_5Omz7lKS0ppzJ9IvPSIzKkna2jjTzF39hu0pcSp80qy4cDZpEFkgRsIWJh1OvUDbpopjFVqX9jftvMZKgYtv-X1FT91wNVIm4I232/s320/android_elements_activities.gif" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Android Activities and Intents</td></tr>
</tbody></table><br />
Below is some simple example code for creating a new intent to launch an <b>Activity </b>named MyActivity. Note the call to the <b>putExtra </b>method which accepts a key name ("content") and a value:<br />
<br />
<pre>Intent myIntent = new Intent();
String packageName = this.getPackageName();
myIntent.setClassName(packageName,
packageName + "." + MyActivity.class.getSimpleName());
<span class="Apple-style-span" style="background-color: #ffe599;">myIntent.putExtra("content", "my content string");</span>
startActivity(myIntent);</pre><br />
Here is the code for the called activity with the <b>Bundle </b>data extracted from the intent. You can then retrieve the passed extra content from the bundle object:<br />
<br />
<pre>public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contentweb);
Bundle bundle = getIntent().getExtras();
String content = <span class="Apple-style-span" style="background-color: #ffe599;">bundle.getString("content");</span>
}
}</pre><br />
All pretty simple when you know how.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-68733713108181792802011-06-13T11:31:00.000+01:002011-06-13T11:31:44.085+01:00Android Development Tools ADT and DDMS Version 11 ReleaseLast week Google released a new version of the <b>Android Development Tools</b> (ADT). If you've not updated to version 11 yet, then <b>DO IT NOW!</b> There are a number of big improvements that will enhance your app development process, particularly regarding layouts and XML editing. Take a look at the video below for details of the update made at Google I/O 2011, if you've been developing on Android for a while, this should really get your juices flowing!<br />
<br />
<iframe allowfullscreen="" frameborder="0" height="349" src="http://www.youtube.com/embed/Oq05KqjXTvs" width="560"></iframe><br />
<br />
If you're not already then you should be following the <a href="http://android-developers.blogspot.com/">Android Developers Blog</a> (or <a href="http://twitter.com/#!/androiddev">@AndroidDev on Twitter</a>).<br />
<br />
<b>How do update my tools in Eclipse?</b><br />
Make sure you are running Eclipse as Administrator, then go to <b>Help > Check for Updates</b>.<br />
Now just step through the sequence, agree to license terms then restart Eclipse when prompted.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com1tag:blogger.com,1999:blog-4612928125526754987.post-60124576837490041652011-06-13T09:52:00.003+01:002011-06-13T11:32:01.833+01:00Cannot install Android Development Tools / DDMSIf you see the following error when updating you Android Development Tools and DDMS in Eclipse on a Windows PC, you need to<b> run Eclipse as Administrator</b>.<br />
<br />
"The operaton cannot be completed. See the details."<br />
<br />
"Cannot complete the install because of a conflicing dependency."<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQtHPDHejdxfsqO6iqSogO3B8ZPBpRlcB0PQ5GypnST6jIYGiJbfU4wwwDv3sI1kr646p8_AQ97x-44GGOV8e4DSwDPLQH8CODjct5ZghkcYic18COhykUhuBlQm99io2oJCwxJcGoGmSa/s1600/android-elements-cannot-complete-install-ddms.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQtHPDHejdxfsqO6iqSogO3B8ZPBpRlcB0PQ5GypnST6jIYGiJbfU4wwwDv3sI1kr646p8_AQ97x-44GGOV8e4DSwDPLQH8CODjct5ZghkcYic18COhykUhuBlQm99io2oJCwxJcGoGmSa/s1600/android-elements-cannot-complete-install-ddms.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><span class="Apple-style-span" style="font-size: small;">Cannot complete the install because of a conflicing dependency</span></td></tr>
</tbody></table>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-46792493328554594222011-06-09T23:37:00.002+01:002011-06-24T11:59:08.223+01:00Creating an Android Preferences Screen<b>How do I add a preferences / setting screen to my android app?</b><br />
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 <b>layout </b>folder.<br />
<br />
The <b>PreferenceScreen </b>layout can be separated into sections with a <b>PreferenceCategory </b>which has a title and is displayed as a dividing bar o the screen. There are several preference type views:<br />
<br />
<b>EditTextPreference</b> - text box entry (text string)<br />
<b>CheckBoxPreference</b> - tickable check box (true/false boolean)<br />
<b>ListPreference</b> - Selection from array of options (text string)<br />
<b>RingtonePreference </b>- Selection of Uri of ring tones stored on device<br />
<br />
A simple example of a preferences screen layout is shown below:<br />
<br />
<b>/res/layout/prefs.xml</b><br />
<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="float: right; text-align: right;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhU_ymhLkpfgnRg9o592rcZbrMdmAXZV1NRf5cqbSsk5xqig6X6iAAOYvvZhl84CWpATAsmzd7hZpTnzah2Nfwbjfj4UwLEr7liq1-_mw4TvR3vf_5_SmoqLStYqSZTo8WAwoAuNflKm4X3/s1600/android-elements-preferences-screen.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhU_ymhLkpfgnRg9o592rcZbrMdmAXZV1NRf5cqbSsk5xqig6X6iAAOYvvZhl84CWpATAsmzd7hZpTnzah2Nfwbjfj4UwLEr7liq1-_mw4TvR3vf_5_SmoqLStYqSZTo8WAwoAuNflKm4X3/s320/android-elements-preferences-screen.png" width="213" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Preferences screen</td></tr>
</tbody></table><pre><?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></pre><br />
The <b>ListPreference </b>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:<br />
<br />
<b>/res/values/strings.xml</b><br />
<pre><?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></pre><br />
Your activity must extend the <b>PreferenceActivity </b>rather than a standard activity. This should be defined as below:<br />
<b><br />
</b><br />
<b>src/<i>your.package.name</i>/Prefs.java</b> <br />
<pre>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);
<span class="Apple-style-span" style="background-color: #ffe599;">addPreferencesFromResource(R.layout.prefs)</span>;
}
}
</pre><br />
Don't forget to add this activity to your manifest!<br />
You can read and write the prefence values in code with the following method examples... <br />
<br />
<pre>// 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();
}</pre><br />
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 <b>theme </b>so that it looks more consistent within your app, simply set the theme for the activity within your manifest as follows:<br />
<br />
<pre><activity android:name=".Prefs" android:theme="@android:style/Theme.Light"></pre><br />
Then your preferences screen will look something like this:<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtEyUVDTpyBURHcGyg1ILx7vVv4MIER4UBdHXrA4H5QWmAOfzp0PA29mzapkf0HffvTBlebHojiLVosS8_gYyGncTHnpAC5gMNmsRtgSGzwlUidIjIKqxNJOqnx6bABUQRdOXg7K-Pj2v1/s1600/android-elements-preferences-screen-light.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtEyUVDTpyBURHcGyg1ILx7vVv4MIER4UBdHXrA4H5QWmAOfzp0PA29mzapkf0HffvTBlebHojiLVosS8_gYyGncTHnpAC5gMNmsRtgSGzwlUidIjIKqxNJOqnx6bABUQRdOXg7K-Pj2v1/s320/android-elements-preferences-screen-light.png" width="213" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Preferences Screen (Light theme)</td></tr>
</tbody></table><br />
<div>Please see my post on <a href="http://android-elements.blogspot.com/2011/05/first-steps-introducing-themes.html">Introducing Themes</a> for more information about themes and styles.</div>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com8tag:blogger.com,1999:blog-4612928125526754987.post-70144107750318679102011-06-06T22:58:00.000+01:002012-09-10T22:35:44.186+01:00Customizing the Title Bar<b>How do I change the title bar for my app?</b><br />
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:<br />
<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">
<b>AndroidManifest.xml</b></div>
<pre style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><application
android:icon="@drawable/icon"
android:label="@string/app_name"
<span class="Apple-style-span" style="background-color: #ffe599;">android:theme="@android:style/Theme.NoTitleBar"</span>
<activity android:name=".Main" <span class="Apple-style-span" style="background-color: #ffe599;">android:theme="@android:style/Theme.NoTitleBar"</span> /></pre>
<br />
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 <b>theme </b>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.<br />
<br />
<b>/res/values/themes.xml</b><br />
<pre><?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></pre>
<br />
<b>/res/values/styles.xml</b><br />
<pre><?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></pre>
<br />
Finally set the theme within the manifest for either the application or individual activities...<br />
<br />
<b>AndroidManifest.xml</b><br />
<pre><application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/Theme.myTheme.TitleBar" ></pre>
danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com2tag:blogger.com,1999:blog-4612928125526754987.post-12906155767036439272011-05-26T14:32:00.002+01:002011-06-30T12:32:30.919+01:00First Steps - Introducing Themes<b>How do I use themes in my app?</b><br />
This post extends my previous post <a href="http://android-elements.blogspot.com/2011/05/first-steps-introduction-to-styles.html">introducing styles</a>, so if you've not used styles in android before I would recommend reading that first.<br />
<br />
A theme is specified for an entire <b>application </b>or individual <b>activities </b>within the manifest. It encapsulates a number of visual style settings, such as text and button styling.<br />
<br />
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 <b>Settings </b>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.<br />
<br />
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:<br />
<br />
<b>Manifest sample:</b><br />
<pre><application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
<span class="Apple-style-span" style="background-color: #ffe599;"> android:theme="@android:style/Theme.Light"</span><span class="Apple-style-span">>
<activity
android:name=".Main"</span><span class="Apple-style-span">
</span> <span class="Apple-style-span" style="background-color: #ffe599;">android:theme="@android:style/Theme.Light.NoTitleBar"</span>></pre><br />
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:<br />
<br />
<b>res/values/themes.xml</b><br />
<pre><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.myTheme" parent="android:Theme.Light.NoTitleBar">
<item name="textSize">20sp</item>
</style>
</resources>
</pre><div><br />
</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">You can then apply your own theme within your project <b>manifest</b>, as shown below.</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><b>Manfiest sample:</b></div><pre>...
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
<span class="Apple-style-span" style="background-color: #ffe599;">android:theme="@style/Theme.myTheme"</span>>
...</pre>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-60651666674760754012011-05-25T09:27:00.000+01:002011-05-25T09:27:17.075+01:00First Steps - An introduction to Styles<b>How do I use styles in my app?</b><br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">Use of styles allows you to define reusable visual settings to help maintain a consistent look-and-feel to your app.</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">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:<br />
<br />
<b>values/styles.xml</b></div><pre><?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></pre><br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">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:</div><br />
<b>values/colors.xml</b><br />
<pre><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myRed">#FF0000</color>
</resources></pre><br />
Now it is simply the case of applying the style within your layouts:<br />
<br />
<pre><?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"
<span class="Apple-style-span" style="background-color: #ffe599;">style="@styles/myWarning"</span> />
</LinearLayout></pre><br />
Note that the <i>style </i>attribute is not prefixed by the <i>android </i>tag.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-59668311698274276782011-05-24T12:27:00.001+01:002011-05-24T12:27:50.241+01:00Referencing a drawable in codeA very quick one here, but I often forget how to get a reference in code to my <b>drawable </b>resources, so here it is...<br />
<br />
<pre>Drawable d = getResources().getDrawable(R.drawable.icon);
</pre><br />
The <b>getResources()</b> method available depending upon <b>context</b>. If you need to reference it from within your own class then you'll need to pass a context in.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-65772812776990796662011-05-24T11:20:00.003+01:002011-06-15T11:03:42.161+01:00First Steps Series, Getting Started with AndroidMy <i>First Steps</i> guides are intended to assist those new to Android development. I thought I should have an index of them all, so here it is.<br />
<br />
1. <a href="http://android-elements.blogspot.com/2011/04/first-steps-1-welcome-to-android.html">Welcome to Android Elements</a><br />
A welcome and how to get started with links to good resources.<br />
<br />
2. <a href="http://android-elements.blogspot.com/2011/04/first-steps-2-android-building-blocks.html">Android Building Blocks</a><br />
The basics of how an app is structured.<br />
<br />
3. <a href="http://android-elements.blogspot.com/2011/04/first-steps-3-my-first-android-project.html">My First Android Project</a><br />
Walkthrough of building your first project; a simple app with a button.<br />
<br />
4. <a href="http://android-elements.blogspot.com/2011/04/first-steps-4-my-second-android-project.html">My Second Android Project</a><br />
Extending the simple app using addition controls and settings.<br />
<br />
5. <a href="http://android-elements.blogspot.com/2011/04/first-steps-4-common-pitfalls.html">Common Pitfalls</a><br />
Common pitfalls and how to avoid them.<br />
<br />
6. <a href="http://android-elements.blogspot.com/2011/05/first-steps-android-project-structure.html">Android Project Structure in Eclipse</a><br />
An overview of the structure of an Android project within Eclipse.<br />
<br />
7. <a href="http://android-elements.blogspot.com/2011/05/first-steps-introduction-to-styles.html">Introduction to Styles</a><br />
Simple guide to using styles when building an app.<br />
<br />
8. <a href="http://android-elements.blogspot.com/2011/05/first-steps-introducing-themes.html">Introducing Themes</a><br />
Expansion of introduction to styles into themes.<br />
<br />
9. <a href="http://android-elements.blogspot.com/2011/06/first-steps-passing-values-to-activity.html">Passing values to an Activity</a><br />
Simple example of passing values into an Activity using an Intent.<br />
<br />
10. <a href="http://android-elements.blogspot.com/2011/06/first-steps-returning-values-from.html">Returning values from an Activity</a><br />
Simple example of returning a value from an Activity.<br />
<br />
I will continue to add to the series over time,danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-61445632801135598312011-05-23T10:26:00.003+01:002011-05-23T11:16:27.672+01:00Displaying the Version number of your app<b>How do I display the versionName from my manifest file in my app?</b><br />
<br />
The <i>versionName</i> value in your project <b>manifest </b>file is a 'friendly' version number that is displayed to the user on the market screen and in the application list. The <i>versionCode</i> value is the integer that allows you to version and publish updates to your app on the market (refer to the official documentation on <a href="http://developer.android.com/guide/publishing/versioning.html">Versioning Your Applications</a>).<br />
<br />
<pre><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidelements.myProject"
android:versionCode="1"
android:versionName="1.0.0">
</pre><br />
You might want to display the version name in your app, on a <i>splash </i>or <i>about </i>screen perhaps. To do this you need to use the <b>PackageInfo </b>class, here's how...<br />
<br />
Add the following imports:<br />
<pre>import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;</pre><br />
Use the following code to display the value in a TextView:<br />
<pre>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);
</pre>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-20015031362313172022011-05-22T22:31:00.000+01:002011-05-22T22:31:35.819+01:00Defining a custom button with background and textcolor styles<b>How do I define a custom button with background and text color styles?</b><br />
<br />
This is a simple guide to styling buttons within your Android app. We start of with a button in your <b>Layout</b>, and set the style to a custom style name:<br />
<br />
<pre><Button
android:id="@+id/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tap me!"
style="@style/button" /></pre><br />
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.<br />
<br />
<b>res/values/styles.xml</b><br />
<pre><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></pre><br />
The background of a <b>Button </b>is expected to be a <b>Drawable</b> (image), but we are able to define this as a <b>shape </b>with an <b>item</b> for each state (pressed, focussed or default). To keep this simple we'll stick to simple colour changes:<br />
<br />
<b>res/drawable/button.xml</b><br />
<pre><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item <span class="Apple-style-span" style="background-color: #ffe599;">android:state_pressed="true"</span> >
<shape>
<solid android:color="#FF0000" />
</shape>
</item>
<item <span class="Apple-style-span" style="background-color: #ffe599;">android:state_focused="true"</span> >
<shape>
<solid android:color="#DDDDDD" />
</shape>
</item>
<item>
<shape>
<solid android:color="#FFFFFF" />
</shape>
</item>
</selector>
</pre><br />
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!danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-24918202300219146642011-05-19T15:52:00.003+01:002011-07-02T22:13:10.279+01:00Advanced Lists: Using class object within ListView<b>How do I build a ListView to display my custom class items?</b><br />
<br />
One of the most common interface elements used in Android apps is the <b>ListView</b>. This presents to the user a scrollable list of tappable items. The best place to start with this is and <a href="http://developer.android.com/resources/tutorials/views/hello-listview.html">Android Developers ListView Tutorial</a> which will cover the basics of creating an <b>activity </b>with the <b>ListView </b>control and displaying a list of items from a string array.<br />
<br />
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.<br />
<br />
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:<br />
<br />
<b>CustomListItem.java</b><br />
<pre><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><span class="Apple-style-span">package com.example.advancedList;
import android.graphics.drawable.Drawable;
public class CustomListItem {
private int mIndex;
private String mLabel;
private Drawable mPicture;
public </span>CustomListItem<span class="Apple-style-span">(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;
}
}
</span></div></pre>Now that we have our class defined, let's create the layout that will be used to display the <b>individual list item</b>, which is a simple <b>RelativeView</b> with an <b>ImageView </b>for the icon and a <b>TextView </b>for the label:<br />
<br />
Create <b>res/layout/list_item.xml </b>:<br />
<pre><?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></pre><br />
Hopefully so far everything has been quite straight forward. We now need to define a custom list adapter that extends the <b>BaseAdapter </b>class, this will allow us to fully control the way the ListView is constructed.<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">Create a class named <b>MyListItemAdapter.java</b>:</div><pre>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;
}
}</pre><div><br />
</div>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.<br />
<br />
We'll call the file <b>res/layout/list_example.xml</b> :<br />
<pre><?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></pre><br />
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 <b>List </b>of our <b>CustomListItem </b>type and add 3 new items to it. We then populate a new <b>ListAdapter </b>using our <b>myListItemAdapter </b>class and assign to it our list of items:<br />
<br />
<b>src/com.example.advancedList/Main.java</b> :<br />
<pre>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;
}
}
});
}
}</pre><br />
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.<br />
<br />
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.<br />
<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com4tag:blogger.com,1999:blog-4612928125526754987.post-66225862631417008412011-05-17T16:34:00.000+01:002011-05-17T16:34:10.707+01:00Best Eclipse ShortcutsThere 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...<br />
<br />
<b>Ctrl + Shift + O</b> = organise and import missing imports<br />
<b>Alt + Shift + R</b> = refactor (rename variable or method)<br />
<br />
<b>Ctrl + 1</b> (one) = Quick fix popup<br />
<b>Ctrl + D</b> = Delete line<br />
<b>Ctrl + O</b> = Outline (easily navigate to parts of project)<br />
<b>Ctrl + M</b> (or double-click tab) = Maximise source when coding<br />
<b>Ctrl + .</b> = Jump next error or warning<br />
<br />
<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><b><br />
</b></div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><b>Alt + <i>UP </i>/ Alt + <i>DOWN</i></b> = Move selection up or down</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><b>Alt + <i>LEFT </i>/ Alt + <i>RIGHT</i></b><i> </i>= Jump to recently edited sections</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><br />
<b>Ctrl + Shift + R</b> = open resource (start typing any file name - like indexed search)<br />
<b><span class="Apple-style-span" style="font-weight: normal;"><b>Ctrl + Shift</b></span> + F</b> - Formats code to settings defined under <i>Window > Preferences > Java > Code Style > Formatter</i>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com1tag:blogger.com,1999:blog-4612928125526754987.post-47864068163969357162011-05-16T11:35:00.002+01:002011-05-20T22:13:37.587+01:00Setting a style on dynamically created view control<b>How do I set a TextView or Button style in code?</b><br />
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 <b>View </b>control programmatically. This is a pain if you are building a layout dynamically.<br />
<br />
To get around this you can create a template layout xml file with the style assigned, for example in <b>res/layout</b> create <b>tvtemplate.xml</b> as with the following content:<br />
<br />
<b>res/layout/tvtemplate.xml</b><br />
<pre><?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" />
</pre><br />
then inflate this to instantiate your new TextView:<br />
<br />
<pre>TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
</pre><br />
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.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com2tag:blogger.com,1999:blog-4612928125526754987.post-47042872296507271932011-05-11T09:41:00.002+01:002011-05-19T14:54:46.840+01:00Adding views to a layout dynamically<b>How do I add a button to my layout in code?</b><br />
<br />
Firstly add the appropriate import to your <b>Activity </b>class for the <b>view </b>to add, in this case a <b>button</b>:<br />
<br />
<pre>import android.widget.Button;</pre><br />
Then create a new button object within the activity <b>onCreate </b>method:<br />
<br />
<pre>Button myButton = new Button(this);
myButton.setText("Tap Me");
</pre><br />
Finally add the button to the layout:<br />
<br />
<pre>LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
layout.addView(myButton);
</pre><br />
Obviously the same logic applies to other views (TextViews, etc).<br />
<br />
You might also want to apply fonts to your controls, if so take a look at <a href="http://android-elements.blogspot.com/2011/05/using-true-type-font-in-your-android.html">Using a True-Type Font in your Android app</a>.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-26976374198990640342011-05-10T21:10:00.001+01:002011-05-11T09:28:24.069+01:00Official Android Ice Cream Sandwich imageTweeted by @AndroidDev earlier today at IO2011...<br />
<br />
<a href="http://twitpic.com/4vxdri" title="Share photos on twitter with Twitpic"><img alt="Share photos on twitter with Twitpic" src="http://twitpic.com/show/thumb/4vxdri.jpg" /></a>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-39814987917498386452011-05-10T13:01:00.003+01:002011-05-11T14:36:51.554+01:00First Steps: Android project structure in Eclipse<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="float: right; margin-left: 1em; text-align: right;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirn64gmCGcpPmLXYmKjPMklSccM1D6aIxLZX9NiBenXVCUiLxHGFsmjdTRrrnWkmXvhCyix5rDH44gyV51ow6jHaBCeAQSVmFDUd7Nw2LiIfHrTmT_w5_qkskz2UkwbCccvaV0ciO0X7tW/s1600/android-elements-project-structure.png" imageanchor="1" style="clear: right; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirn64gmCGcpPmLXYmKjPMklSccM1D6aIxLZX9NiBenXVCUiLxHGFsmjdTRrrnWkmXvhCyix5rDH44gyV51ow6jHaBCeAQSVmFDUd7Nw2LiIfHrTmT_w5_qkskz2UkwbCccvaV0ciO0X7tW/s1600/android-elements-project-structure.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Android Project structure in Eclipse</td></tr>
</tbody></table>This article is a quick guide to the breakdown of the project structure of a typical, simple Android project within Eclipse. The numbered items below refer to the image to the right.<br />
<ol><li>Project root folder (see 7 for details of individual files)</li>
<li><b>src </b>folder. This is where your java code files are stored.</li>
<li><b>package </b>folder. This is organised by package name with the java class files within.</li>
<li><b><i>Main.java</i></b> is a java class file, in this case the main activity. Note the exclamation denoting a compilation warning.</li>
<li><b><i>Web.java</i></b> is another java class (without warnings or errors).</li>
<li><b>gen </b>folder. The <b>generated </b>compiled files when a project is built. You do not need to venture into this folder.</li>
<li><b>Google APIs</b> folder. The API library folder.</li>
<li><b>assets </b>folder. This is where you place additional assets for use in your project, such as font (ttf) files.</li>
<li><b>res </b>folder. This is where the <b>resource</b> files are stored, such as your drawables (images), layouts and string values.</li>
<li><b>drawable-hdpi</b> folder. High density drawables (images) for use in your project.</li>
<li><b>drawable-ldpi</b> folder. Low density drawables (images) for use in your project.</li>
<li><b>drawable-mdpi</b> folder. Medium density drawables (images) for use in your project.</li>
<li><b>layout</b> folder. This contains the XML layout files that define the screens in your project.</li>
<li><b><i>main.xml</i></b>. This is the layout for the Main activity, defined in Main.java.</li>
<li><b><i>web.xml</i></b>. This is the layout for the Web activity, defined in Web.java.</li>
<li><b>values</b> folder. This is where your string (text) definitions are stored. To support multiple languages you would find a values folder per language, for example values-fr.</li>
<li><b>strings.xml</b>. A standard XML file containing named string definitions.</li>
<li><b>AndroidManifest.xml</b> - The hub of your project containing the details on the Activities, Permissions within your app.</li>
<li><b>default.properties</b> -An auto-generated configuration file storing the basic project properties.</li>
<li><b>proguard.cfg</b> - ProGuard can be used to obfuscate your code to prevent nasty code thieves from stealing your secrets. By default this is not applied to the code but the configuration file is still present.</li>
</ol><div>Typically you will place any additional referenced Java libraries (.jar files) into a <b>libs </b>folder.<br />
<br />
Hopefully this will help an Android newbie opening up a new project for the first time.<br />
<br />
</div>danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com1tag:blogger.com,1999:blog-4612928125526754987.post-89330538267490618442011-05-06T16:45:00.003+01:002011-06-07T15:03:38.957+01:00Using a True-Type Font in your Android appAndroid supports <b>true-type fonts</b>, but these have to be set in code, you cannot specify the fonts in the layout XML.<br />
<br />
Firstly copy the font file into your <b>assets </b>folder. I usually create a <b>fonts </b>sub-folder:<br />
<br />
<pre>project/assets/fonts/myfont.ttf
</pre><br />
Second, and finally, apply the font to a TextView in code:<br />
<br />
<pre>TextView tv = (TextView)findViewById(R.id.TextView1);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
tv.setTypeface(face);
</pre><br />
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.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-49974218327130133732011-05-04T10:12:00.003+01:002011-05-16T14:11:08.072+01:00How to Fix Screen Orientation<b>How do I stop my Android app rotating?</b><br />
<br />
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 <b>activity </b>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.<br />
<br />
To fix your screen orientation, simply set the <b>screenOrientation</b> attribute of the <b>activity </b>within your <b>project manifest</b>, as shown below, to either <b>portrait </b>or <b>landscape</b>:<br />
<br />
<pre><activity
android:name=".myActivity"
<span class="Apple-style-span" style="background-color: #ffe599;">android:screenOrientation="portrait"</span>>
</pre><br />
You can also do the same thing in code:<br />
<br />
<pre>myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
</pre><br />
Please refer to the <a href="http://developer.android.com/guide/topics/manifest/activity-element.html">official documentation</a> for more details.danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0tag:blogger.com,1999:blog-4612928125526754987.post-88699170941234778612011-04-28T14:32:00.002+01:002011-05-17T16:35:43.498+01:00Regular Expressions in AndroidIf you are not familiar with <b>regular expressions</b>, then it is well worth spending some time finding out about them. Basically a regular expressions allow you to define a and search for a <b>pattern</b> of text within a string, to pick out an email address for example. Head over to <a href="http://www.regular-expressions.info/">regular-expressions.info</a> and find out more, it may seem overly complicated at first, but you will often find you cannot do without them. There are also plenty of sites for testing patterns against, <a href="http://regexpal.com/">regexpal.com</a> is a good simple one.<br />
<br />
Right, let's get to the code. To handle regular expressions in Android you use the standard Java classes, so if you are familiar with these then there is nothing more to learn. Otherwise, the first thing to do is add the following <b>import </b>references to your class:<br />
<br />
<pre>import java.util.regex.Matcher;
import java.util.regex.Pattern;
</pre><br />
My example method will match a defined pattern in the variable myString. If a match is found then the first match (there may be more than one) is returned for use:<br />
<br />
<pre>private String findMatch(String myString) {
String match = "";
// Pattern to find code
String pattern = "[0-9]{8}"; // Sequence of 8 digits
Pattern regEx = Pattern.compile(pattern);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
return match;
}
</pre><br />
Hopefully this simple guide is enough of an introduction to the basics to get you going. There are many good resources on the web to help you build patterns and also libraries of commonly used patterns, <a href="http://regexlib.com/">regexlib.com</a> for example. Now you'll be knocking out expressions in no time!danhttp://www.blogger.com/profile/00705575879554658733noreply@blogger.com0