SyntaxHighlighter

Friday, September 24, 2010

Android Programming Jumpstart – 6

image
  This is lab 6 in my ongoing series of jumpstart Android programming tutorials.
  This lab will focus on selectable ListViews.


Here are some terms that you’ll need to understand to work with ListViews:

  • Context
    • Interface to information about an application environment
    • Typically when a context parameter is needed for your app you will use (this)
  • Adapters
    • The bridge between a View and the data for that viewimage
    • Provides access to the data items
  • ArrayAdapter
    • The ArrayAdapter constructor takes three parameters:
      • The Context to use (this)
      • The resource ID of a view to use
      • The actual array or list of items to show
    • By default, the ArrayAdapter will invoke toString() on the objects in the list and wrap each of those strings in the view designated by the supplied resource.
    • android.R.layout.simple_list_item_1
      • a built in resource that turns those strings into TextView objects styled in a particular way.
    • Definitions for some built in resources can be found here
  • Listeners
    • Interface to setup callbacks for actions on your widgets
    • Use to set up link between a button and onClick

  • ListView
    • To use you will need to define one in your layout
      • android.R.layout.simple_list_item_1
      • android.R.layout.simple_list_item_single_choice
      • android.R.layout.simple_list_item_multiple_choice
    • Assign data to it using setAdapter()
    • Assign functionality to catch users selections using a Listener using setOnItemClickListener()
    • If your View is really just your list, you can make things easier on yourself by having your activity extend ListActivity
      • It will then construct the full screen list for you
      • You must name your ListView @android:id/list

Check out the two different ways of working with a ListView below.  In this first example everything is setup in onCreate().

image

image

In this example everything we have broken it out.
image 

image

Here are some different types of usage for a ListView. 
It is quite versatile and can be used for single or multi selections.
image

Wednesday, September 22, 2010

Android Programming Jumpstart – 5

image This is lab five in my ongoing series of jumpstart Android programming tutorials.
This lab will focus on containers.






We need containers to better organize our widgets
  • LinearLayout
    • Use to lineup contents in rows or columns
    • :orientation property - set the value to be horizontal for a row or vertical for a column.
    • Fill up the space – widgets inside a LinearLayout must set layout_width and layout_height, by a dimension, wrap_content, or fill_parent
    • :layout_weight property – sets what proportion of the free space a widget gets. If there are two widgets and you set one’s weight to 1 and the other one’s to 2, the second will get twice as much of the free space.
    • :layout_gravity – alignment - default for LinearLayout is align top left.
      • For LL columns values are left, center_horizontal, and right
      • For LL rows – default to let the widgets align along their bottom, but you could use center_vertical to center along the row’s vertical midpoint
    • :padding property – use this to insert whitespace between widgets. Using this property will add padding around the widget equally.
      • If you need the padding to vary, use android:padding<Left, Right, Top, Bottom>
  • RelativeLayout
    • Contents are laid out based on their relationship to the other widgets and the parent container
    • Alignment is based on total size – includes padding if any
    • Set relationships to parent container using:
      • android:layout_alignParrent<Top, Bottom, Left, Right>
      • android:layout_center<Horizontal, Vertical, InParent>
      • These are set using true or false
    • Set Relationships to other widgets using:
      • Referenced widgets need to have an id tag and should be referenced using “@id”
      • android:layout_<above, below, toLeftOf, toRightOf>
      • android:layout_align<Top, Bottom, Left, Right, Baseline>
      • android:layout_toRightOf = "@id/widget_a"
image
image
  • TableLayout
    • Layout a grid just like HTML tables
    • TableLayout controls the overall characteristics of the container
    • Your widgets go into TableRow containers
    • Columns are controlled less directly than in HTML
      • Think one column per widget in your widest row
      • Widgets can span columns using android:layout_span
      • Fills left to right or specify the number using android:layout_column
      • Like your wallet – zero based numbering
      • Confusingly, Android will let you place widgets between rows without being in a TableRow container, but its width will automatically be set to fill_parent
      • Columns size themselves to the width of the widest widget in the column, but you can control this behavior by setting properties on the TableLayout itself using:
    • android:<stretchColumns, shrinkColumns, collapseColumns>
    • These take a column number or a comma separated list of column numbers
  • Scrollview
    • Given that the Android device will have limited screen area, at some point you will have to use scrolling
    • Can only have one child element – but that child can have many elements
    • There is a HorizontalScrollView, but generally users mind scrolling up and down less than side to side
image

Some sample code
image

Android Programming Jumpstart - 4

image This is part four of my series on jump-starting your Android programming experience. 
This lab focuses on Android Widgets.  The tutorials from here on out will gather speed and expect that you do some research of your own.  Not so much spoon feeding from now on.




  • TextView
    • Can do all the things you would expect, set bold, italic, set color
    • Can set the text in code, XML, or via a resource defined elsewhere res/values/strings.xml (@string/hello)
  • Button
    • Derives from TextView
    • Using 1.6 or better now can set the associated method an additional way to the OnClickListener
    • In the XML attributes for the button add android:onClick=“functionName”
  • Images
    • ImageView, ImageButton
    • In main.xml need to include android:src attribute
    • supports common still-image formats PNG, JPG, and GIF
  • EditText
    • Derives from TextView
    • Typical Edit box properties
      • Also items like autoText, digits, singleLine
  • Checkbox
    • Derives from CompoundButton which derives from TextView
    • Typical checkbox properties, isChecked, setChecked, toggle
    • Can wire up a handler right from the XML just like the button or set up the OnCheckedChangeListener
  • RadioButton
    • Derives from CompoundButton which derives from TextView
    • Place inside a RadioGroup
    • Typical properties, check, clearcheck, getCheckedRadioButtonId
  • Useful functions
    • setEnabled, isEnabled, requestFocus, isFocused, getParent, findViewById
    • android:autoText - control if the field should provide automatic spelling assistance
    • android:capitalize - control if the field should automatically capitalize the first letter of entered text (e.g., first name, city)
    • android:digits - configure the field to accept only certain digits
    • android:singleLine - control if the field is for single-line input or multiple-line input
  • Good Resource
Use your IDE to try to replicate what I have depicted below.  Be creative and use your own names/labels.
image



image


image

Some sample code for you
public class MyWidget101 extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }// end onCreate

    // This is the method wired to my button in main.xml    public void simpleBtnClick(View theButton)
    {
        Toast.makeText( getApplicationContext(),
                        "Dude, you clicked my button.",
                        Toast.LENGTH_SHORT  ).show();
    }


    // This is the method wired to my checkbox in main.xml    public void simpleCheckbox(View theCheckBox)
    {
        // cast the passed in view to a Checkbox        CheckBox chkbox = (CheckBox)theCheckBox;
        // update its text        if( chkbox.isChecked() )
        {
            chkbox.setText("Checked");
        }
        else
        {
            chkbox.setText("Unchecked");
        }
        /* OR we could have done it like this
        if (((CheckBox)theCheckBox).isChecked())
        {
            ((CheckBox)theCheckBox).setText("1Checked");
        }
        else
        {
            ((CheckBox)theCheckBox).setText("2Unchecked");
        }
        */
    }// end simpleCheckbox



    // This is the method wired to my radio buttons in main.xml
    public void simpleRadioButtonClick(View theButton)
    {
        RadioButton rb      = (RadioButton)theButton;
        EditText    editBox = (EditText)findViewByID(R.id.EditText01);
        editBox.setText(rb.getText());
    }
}// end class MyWidget101

Android Programming Jumpstart - 3

image This is part three in my series of quick tutorials to get you up and started programming Android applications. 
For this lab we will be looking more into XML defined layouts for your GUIs.





A common approach is to use an XML based file to layout the UI.
  • Specifies the relationships of widgets with each other and their containers
  • Very similar to laying out a webpage
  • Located in res/layout – aka main.xml
  • Your layout file will be a tree of XML elements
Elements attributes AKA properties specify the its look and behavior
  • You can access these elements from your Java code
Similar to HTML/Javascript programming and you can use third party tools to create the UI layout.
Here is a project close to where we left off in part 2.
image
By the by – I have found that Eclipse can be twitchy if you try to run and the main.xml has focus in the IDE… 
My recommendation – don’t build or try to install from the IDE if an XML file has focus.
image
image
XML element attributes
  • You won’t need to reference all your widgets in your Java code, but using an ID will allow you to do that  -  @+id/[your ID] – this creates a new ID resource
  • layout_width, layout_height
    • These can be used to specify the size of your widget. The value could be one of the constants below or an actual dimension. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
    • FILL_PARENT – make the view wants to be as big as its parent minus padding
    • WRAP_CONTENT – make the view wants to be just big enough to enclose its content plus padding
  • text
    • The text value you want displayed. This can be updated during runtime.
  • Much more



  • SetContentView now uses our layout we defined in main.xml







  • Used findViewById to get the Button instance using the @+id value we defined







  • Used an anonymous inner class to override the onclick handler
    image
    The complete application – same as what we did in part 2.
    image
    In the next lab we will more into the widgets and how to use them.
  • Android Programming Jumpstart - 1

    image These series of labs are intended to give interested parties a quick ramp up on programming for the Android environment.  I will converting these to a wiki page in the future so that others can add to them.
    I will not be spending much time regarding setting up a tool of choice.  I normally use Motodev or Eclipse.  The setup for these is already well documented online and the Motodev installer takes care of a lot for you.  First lets review some basic terminology that will be used a lot.

    • Activities
      • User interface building block,
      • Similar to PC window or dialog
      • Short lived, can be shut down anytime
    • Content Provider
      • Provide abstraction of data stored on device that is accessible by multiple apps
      • Maintain control over how your data is access
      • Short lived, can be shut down anytime
    • Services
      • Designed to keep running independent of an activity
      • Background processing
      • example: music player
    • Intents
      • System messages, notifying apps of events
      • Can respond to and create your own
    • View
      • Building block for UIs
      • Base class for widgets
    • ViewGroup
      • Subclass of View
      • Base class for layouts, containers for Views or ViewGroups
    What’s built into the environment
    • Storage
      • Package data files for things that don’t change like icons and help files
      • Get space on device or SD card for databases or files storing user entered data
    • Network
      • Most devices internet ready
      • Can access Java sockets
      • WebKit Web Browser widget
    • Multimedia
      • Play back and record audio and video
    • GPS
      • Most devices have GPS
    • Phone
      • Apps can start phone calls, send and receive text messages
    Project Folder Structure
    • AndroidManifest.xml
      • key element
      • Lists all activities, services, permissions, API level
      • Used by Android Market to filter what apps are offered. So min Android 2.0 apps won’t be offered to someone running Android 1.5
    • default.properties – generated file – do not touch
    • build.xml – not needed if using IDE, Ant script, generated
    • src/ - java source code
    • gen/
      • Android build tools use this for source code they generate
      • generated – do not touch
      • R.java will be in here and is used to reference items
    • –es/ - icons, layouts
    • bin/ - compiled output
    • assets/ - files you want packaged with your app
    • libs/ - use this folder to hold third party JARs
    • tests/ - holds separate project for testing yours – I haven’t used this yet
    • APK file – the zip archive that is essentially the android executable
    AndroidManifest.xml
    • uses-permission element – indicates what permissions your app needs
    • permissions elements – declares the permissions that Activities and Services require other apps to have in order to interact with your app
    • instrumentation elements – indicates the code that is invoked on key system events
    • uses-library elements – attach to optional Android components
    • uses-sdk element
    • indicate the version of Android SDK the app was built for
    • Set minSdkVersion for Android Market
    • application element – define your app
    • activity elements
    • android.name – class implementing the activity
    • android.label – display name for the activity
    • intent-filter – under what conditions the activity will be displayed
    • receiver – non-activities that should be triggered under certain conditions
    • provider – components that supply data to activities
    • services – longer running code that can operate independently
    Android Emulators
    • Setup via AVD Manager
    • Meant to simulate real Android devices
    • Must specify target
    • What type of device will the AVD pretend to be
    • Can’t edit after creating
    Android SDK and AVD Manager
    image
    • Can be launched from within Motodev or via command line
    • Available Packages - Install and update Android SDK components
    • Select the components to install
    • Updates will also be listed here
    • Can add additional sites to look for components
    • Virtual Devices - Create and edit Android Virtual Devices (AVDs) that provide the emulator for testing apps
    • Each AVD behaves as a totally distinct device, so installing your app on one AVD does not affect any other AVDs that you have created.
    • More detailed instructions are available on the Android developer site
    • http://developer.android.com/sdk/adding-components.html
    • Creating the AVD
      • Google info
      • Name the AVD
      • I like to include the version
      • Set the target level
      • Can leave the rest as is
      • After you create the AVD you will see it listed in the devices tab
      • Start it!
    image

    image 


    Creating a new project requires: 
    •   Project name
    •   Contents location
    •   Target
    •   App Name
    •   Package Name – must have at least two identifiers
    •   Activity Name – if creating
    •   Min SDK Version - optional













    image

    What you can find in your project Folder Structure
    • src/ - java source code
    • gen/
    • Android build tools use this for source code they generate
    • generated – do not touch
    • R.java will be in here and is used to reference items
    • assets/ - files you want packaged with your app
    • res/ - icons, layouts
    • AndroidManifest.xml
    • key element
    • Lists all activities, services, permissions, API level
    • Used by Android Market to filter what apps are offered. So min Android 2.0 apps won’t be offered to someone running Android 1.5
    • default.properties – generated file – do not touch
    • build.xml – not needed if using IDE, Ant script, generated
    • bin/ - compiled output
    • libs/ - use this folder to hold third party JARs
    • tests/ - holds separate project for testing yours – I haven’t used this yet
    • APK file – the zip archive that is essentially the android executable
    AndroidManifest.xml
    • Every application must have an AndroidManifest.xml file in its root directory. The manifest presents information about the application to the Android system, information the system must have before it can run any of the application's code
    • uses-permission element – indicates what permissions your app needs
    • permissions elements – declares the permissions that Activities and Services require other apps to have in order to interact with your app
    • instrumentation elements – indicates the code that is invoked on key system events
    • uses-library elements – attach to optional Android components
    • uses-sdk element
    • indicate the version of Android SDK the app was built for
    • Set minSdkVersion for Android Market
    • application element – define your app
    • activity elements
    • android.name – class implementing the activity
    • android.label – display name for the activity
    • intent-filter – under what conditions the activity will be displayed
    • receiver – non-activities that should be triggered under certain conditions
    • provider – components that supply data to activities
    • services – longer running code that can operate independently
    image

    Saturday, September 11, 2010

    Android Programming Jumpstart - 2

    imageThis is part two of the series of labs providing quick ramp up on programming for the Android environment.

    As I stated in part 1, normally I use Motodev or Eclipse. 

     

     

    This is where we left of last time.  We had made our first hello world style project.  But it wasn’t very impressive.image

    Let’s expand the project to add a button that will pop up a message to the user. 

    It isn’t very difficult to do but it will expose a few new ways of working with the IDE.  In your IDE project outline under the res/layouts folder you will find your main.xml.  This is where you can either edit the XML directly (which I like to do) or you can use the Layout editor to drag in a button and then use the properties to update the Button’s attributes.  The layout view is not up to the level of a MS Visual Studio project, but it is still useful.  Feel free to deviate from what I have defined below and try it for your self.

    image

    Let’s review a little bit about the IDE.  One of the things is that the compiler will try to help you by catching that there are imports you need.  However as your projects get larger you may want to turn off the auto-build feature.  In the example below we haven’t finished typing in the code for a Toast (a pop up type of notification) so it flags as an error.  Also displayed are some of the nice information features of Motodev/Eclipse.  Play with your IDE to learn more.  Don’t be afraid.

    image 

    Here are the basic steps needed to be done at this point.

    image

    Now when we build the project and run it on our AVD we get the following.  Congratulations, you created an interactive Android widget!

    image

    Thursday, September 9, 2010

    Splitting windows in Eclipse and Motodev

    This one is just so I won’t forget myself.  I am used to using a split window view Visual Studio and wanted to do the same thing in Motodev.  Unfortunately it doesn’t have the exact same type of capability, but does have a similar way to do it.

    1. Open the file in your editor view,
    2. From the main menu select Window –> New Editor,
    3. Another editor window will open for the file you are working on.
    4. Then you can drag it below the file you wanted to “split” and get  similar approach.  You just lose a little screen space.