Thursday, May 5, 2011

Landing Activity Icons The Easy Way

Many Android applications include a landing activity or a "main page" full of icon options. Typically this activity does little more than throw intents to launch other Activities when a user clicks one of the icons. In this post, I'm going to take advantage of the onClick, tag, and drawableTop attributes of TextView to make this work with very little code.

 Let's imagine that I'd like to write a media playing application that includes main activity icons for Music, Photos, and Video. For each icon on the landing activity, I'm going to use just a tiny bit of xml in my layout:

<TextView
android:text="Music"
android:drawableTop="@drawable/icon_music"
style="@style/mainicon"
android:tag="com.example.action.MUSIC"/>


First, you'll notice that the text and drawableTop attributes specify the drawable and the text for the icon. Using drawableTop keeps you from having to define a linear layout for each icon to stack the icon on the text. Here you can do it with just the TextView element and that's all.

Second, notice the style attribute. Here's the style I've defined for a main icon:

<resources>
<style name="mainicon">
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:gravity">center</item>
<item name="android:clickable">true</item>
<item name="android:onClick">click</item>
</style>
</resources>


The obvious bits of style specify the height, width, and gravity. What isn't so obvious is the definition of clickable and onClick. Basically, the onClick attribute is telling every View that has this style to execute the method called "click" in the parent Activity. But wait, hows that going to work? We're telling every icon to run exactly the same code. Here's the code for the click event method:

public void click(View view) {
   String action = (String) view.getTag();
   Intent intent = new Intent(action);
   startActivity(intent);
}


The click method pulls the tag from the view that was clicked and fires an Intent using that string as the action. Take a look again at the XML that defines our music icon. See the tag attribute?

Now, there's one final step to make this work. The AndroidMainifest.xml must be modified so that the music Activity knows how to receive the intent we're throwing. Easy:

<activity android:name=".Music">
<intent-filter>
<action android:name="com.example.action.MUSIC"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>


The intent filter will route all of the action.MUSIC intents to the Music activity. Hopefully this will simplify your code and clean things up a bit Have fun.

No comments:

Post a Comment