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.

    Monday, August 30, 2010

    Telnet and your Android Emulator

    Did you know you can telnet into an Android emulator/AVD?  Assuming that you have telnet installed and have created an AVD, its very easy. 
    1. On your Android AVD’s title bar you should see the name of your emulator with some numbers pre-pended to it.  That is the console port number of your AVD.
    2. Open a command window and type “telnet localhost <the number>” NOTE – don’t type the brackets, just the number.
    3. Your command window should be updated to show the connection.  Type help to get a valid command list.

    Sunday, August 29, 2010

    Using Multiple Activities in Android

    I’m new to having to deal with multiple Activities and have learned a lot as I have gone about implementing an app with many Activities.  Lessons Learned:
    (1) Don’t try to keep a list of Activities or Activity instances in your main class.  Not only does this waste memory, but when you go to start an Activity you’re not really doing what you think. 
    (2) Activities aren’t always around when you need them AKA use Intents.
    (3) Use Intents and possibly a little bundling, and the whole thing gets easier.
    (4) The Activities constructor is pretty much useless – use onCreate!
    I come from a Windows programming background where I didn’t have to worry little things like memory and batteries.  I was used to the old way of doing business where I could create a bunch of screen classes, instantiate them all, and then just show/hide or swap out whatever I wanted depending on the user’s choices.  Yes, life was good.  :)  Then this cool new Android stuff beckoned and off we go…  The old ways won’t work.
    The particular problem that I was trying to solve was this.  The app comes up and has 3 screens (Activities, I know I like my windows terms).  The user needs to be able to switch screen to screen.  Simple right?  Easy enough for even a newbie like me to create 3 Activities, create 3 Intents that use those classes, and fire them up right?
        /**
         * onCreate(Bundle savedInstanceState)
         * Called when the activity is first created.
         */

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main); 
            // Create Activity instances
            Activity theActivity1 = new Activity1();
            Activity theActivity2 = new Activity2();
            Activity theActivity3 = new Activity3();

            theActivity1Intent = new Intent(this, Activity1.class);       
            theActivity2Intent = new Intent(this, Activity2.class);
            theActivity3Intent = new Intent(this, Activity3.class);

        }// end onCreate
    For the sake of this example we will assume that the user clicks a button that tells the app which screen to display first.  So in the button click we have
    startActivity(theActivity1Intent);
    and then off we go displaying the first Activity!  What’s wrong with this picture?  A couple of things actually.  (1) we wasted time even calling new on the three Activity classes.  Notice that the Intent is fed in that it is associated with the Activity1 class – not theActivty1 – two very different things.  (2) we really haven’t given ourselves a very good way to pass any needed information into the Activity that might be needed for its display.  (3) we have know way of getting any data back from the Activity, for example, where did the user choose to navigate to next.  Fortunately Android has built in some features that make this easier for us.  Review the updated onCreate
    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main); 

     
       theActivity1Intent = new Intent(this, Activity1.class);
       theActivity1Intent.putExtra("LeftScrn",  "Activity3");
       theActivity1Intent.putExtra("RightScrn", "Activity2");
       theActivity1Intent.putExtra("Tag", A1);


       theActivity2Intent = new Intent(this, Activity2.class);
       theActivity2Intent.putExtra("LeftScrn",  "Activity1");
       theActivity2Intent.putExtra("RightScrn", "Activity3");
       theActivity2Intent.putExtra("Tag", A2);


       theActivity3Intent = new Intent(this, Activity3.class);
       theActivity3Intent.putExtra("LeftScrn",  "Activity2");
       theActivity3Intent.putExtra("RightScrn", "Activity1");
       theActivity3Intent.putExtra("Tag", A3);



       theIntentList = new ArrayList<Intent>();
       theIntentList.add(theActivity1Intent);
       theIntentList.add(theActivity2Intent);
       theIntentList.add(theActivity3Intent);
       theMaxIndex = theIntentList.size()-1;

    }// end onCreate
    See, we don’t to instantiate or save Activities, we need to define the Intents and then let Android do the work.  Additionally notice that we are using the putExtra Feature to assign name value pairs to the Intent that can be used, or ignored, by the Activity.  Next review the updated onClick call to start the Activity
    public void onClick(View v)
    {

       // Launching the activity to get a result when it finished. When this
       // activity exits, onActivityResult() method will be called with the
       // given requestCode. Using a negative requestCode is the same as calling
       // startActivity(Intent) (the activity is not launched as a sub-activity).
       // parameters
       // intent - the intent to start
       // request code - If >= 0, this code will be returned in onActivityResult()
       //                when the activity exits.

       startActivityForResult( theActivity1Intent,
                               theIntentList.get(theCurrIndex)
    .getExtras()
                                                              .getInt("Tag"));
    }

    Now we can get some data back and decide how to proceed from there.  This code is a little more lengthy.
    /**
       * onActivityResult
       * Called when an activity you launched exits, giving the requestCode you
       * started it with, the resultCode it returned, and any additional data.
       * The resultCode == RESULT_CANCELED if the activity explicitly returned
       * that, didn't return any result, or crashed during its operation.
       * You will receive this call immediately before onResume() when your
       * activity is re-starting.
       * I am using this function to determine if I need to nav left or right
       * Parameters
       * @param requestCode - The integer request code originally supplied to
       *                      startActivityForResult(), allowing you to identify
       *                      who this result came from.
       * @param resultCode  - Integer result code returned by the child activity
       *                      through its setResult().
       * @param data        - An Intent, can return result data to the caller
       *                      (various data can be attached to Intent "extras").
       */

      protected void onActivityResult(int requestCode,

                                      int resultCode,
                                      Intent data)
      {
         // Regardless of which screen exited and is telling to go left or right
         // we need to determine the left and right indexes

         // Left index - if the current index is not zero then left is minus one
         //              otherwise if zero the actual left is the end of the list

         int leftIndex  = (theCurrIndex != 0) ? theCurrIndex-1 : theMaxIndex;
         // Right index - if the current index is the end of the list then right
         //               the the beginning of the list or zero, otherwise right

         //               is plus one
         int rightIndex = (theCurrIndex == theMaxIndex) ? 0 : theCurrIndex+1;

         // Get the extra from the Intent that tells us left or right.
         // NOTE - you need to check for null, if the user presses the back btn
         //        there will not be an Intent attached and data will be null

         String dir = "";
         if (null!= data)
         {
            dir = data.getStringExtra("Go");
         }
         // the Activity set this value if it was returning normally
         if (RESULT_OK == resultCode)
         {
            if ( 0 == dir.compareTo("left"))
            {
               theCurrIndex = leftIndex;
            }
            else if (0 == dir.compareTo("right"))
            {
               theCurrIndex = rightIndex;
            }
            else
            {
               // intentionally do nothing        }
            // Get the Intent
            Intent nextIntent = theIntentList.get(theCurrIndex);
            // Get the tag
            int    tagValue   = theIntentList.get(theCurrIndex)

                                             .getExtras().getInt("Tag");
            // Start the new Activity
            startActivityForResult( nextIntent, tagValue);


         }// end if (RESULT_OK == resultCode)
      
     
      }// end onActivityResult

    Not shown is how in the actual Activity class before it returns to the main Activity is how it does its own putExtra on the returning Intent.  Additionally the Activity calls its onFinish().  This lets Android know that we are done with this Activity and lets it do any needed management.
    I’m sure there are slicker/better ways to handle this.  Its what I’ve got for know.  Feel free to let me know if you know of a smarter way!

    Blogging isn’t as easy as it looks

    image This is not really an Android focused post so much as it is a post on posting.  How’s  that for an opening sentence?  As someone used to writing in Word and PowerPoint it was surprisingly hard to get my first posts formatted like I wanted.  Just too used to be able to copy and paste images and copy in code snippets.  I was under the impression that I could continue that normal way of business.  This was reinforced by the fact that my first blog experience (with SharePoint) I was able to pretty much copy from Word into the SharePoint blog interface.  Even then the whole process felt like it was much harder than it should be.  I had an even ruder awakening when I tried to copy over a blog from SharePoint hosted to Blogger.  Having code snippets (XML for that matter) does not make the Blogger interface happy.  After quite some time hunting around I found my tool of choice – for now – Windows Live Writer.  So far it seems to be doing a good job of keeping me in my comfort zone and streamlining the publishing.  If you have something better let me know!  I’m not shy about upgrading if it makes things easier.
    One thing that did throw me off about blogger was the width of the actual blog interface.  The default is surprisingly narrow to me and it was more difficult than expected to update.  But find it I did.  I’m posting it here since I’m sure I’ll forget how I did it later. 
    (1) Go to your design tab in your Blogger dashboard
    (2) Select Edit HTML and then search for something like this:
    <b:variable default='930px' name='content.width' type='length' value='1200px'/>
    (3) Change the value to what you want and save.  DISCLAIMER – you may want to backup your original template first.

    Friday, August 27, 2010

    Break out your Layout

    Recently I faced the issue of needed to reuse a particular layout on multiple screens.  If you are like me you have to copy and paste code.  Anytime I find I need something more than once I look for a way to get some reuse.  Luckily Android has provided a few easy ways to do this when creating your screens.  I'm actually using 2 different ways on my current program.  Take a look at <ViewStub> and <include>, both work very well.
    Let’s look at how we can use these in a layout file.
    <LinearLayout>
        <!-- The include will load in the layout files -->
        <include android:id="@+id/theStatusBar" layout="@layout/statusbar" />
        <!-- The ViewStub will wait for you to tell them to inflate -->
        <ViewStub android:id="@+id/theView1Stub"
                  android:layout_width ="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout="@layout/view1" />
        <ViewStub android:id="@+id/theView2Stub"
                  android:layout_width ="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout="@layout/view2" >
    </LinearLayout>
    So in the snippet above, we have two includes and two ViewStubs. The significant difference being the <include> will automatically load in the layout specified and inflate/display it in your Activity’s layout. So when the Activity’s onCreate is called and the setContentView is specified Android will do the magic for you.
    Why use <ViewStub> too? Perhaps you need to customize your screen depending on some flag or parameter. Since a ViewStub is not inflated until you tell it, it can be useful. In this example I have a base class that extends from Activity that has the above in its layout file. I also have two other Activity classes that inherit from it. Since the status bar is needed by both screens, the base class can handle loading and controlling that for its children. Each child in its onCreate can then inflate itself once it is started. So in each child class is a line of code to inflate their applicable Viewstub
    // inflate ourselves into the layout ViewStub
    View view = ((ViewStub) findViewById(R.id.theView1Stub)).inflate();
    Check out these online resources here for more info:
    Layout Tricks: Creating Reusable UI Components
    Layout Tricks: Creating Efficient Layouts
    Layout Tricks: Using ViewStubs
    Layout Tricks: Merging Layouts