Handling HTML content on a TextView is simple as far as the HTML coming in contains a few tags that are by default supported by Android. Simple formatting like bold, italics, font sizes can be handled without even coding a single extra line.
Say, if you have a TextView tv, and there's some HTML string with bold and italicized text, bringing it up on the TextView is pretty simple.
One line code for that:
tv.setText(Html.fromHtml(source));
where the source is actually your HTML string. This works perfectly. But how do we show images if there are any. Well, it's a bit tricky. You have to use the other method that takes in an ImageGetter and a TagHandler.
fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
The tagHandler is for situations where you wish to handle specific tags differently. I didn't wish to do that, so I just passed null there.
Now comes the main task. How do you get the image on to the TextView!!!!
Implement the Html.ImageGetter's getDrawable method which handles downloading the image, or accessing it from the net, and then create a drawable and return that object.
static ImageGetter imgGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = null;
drawable = Drawable.createFromPath(source); // Or fetch it from the URL
// Important
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
return drawable;
}
};
and use the method on the TextView like this.
tv.setText(Html.fromHtml(source, imgGetter, null);
This will load the TextView with the image. But this call to the getDrawable method is not asynchronous. So, until and unless that method returns, you UI will be blocked. In my case, I am creating the drawable from a local image, so, it didn't take much time. But, if you want to fetch an image from the web, you have to make this call in a separate thread, so that the UI is not blocked.
So, check your HTML string if they contain any images that have to be downloaded. If you find any, create a thread that download that image, saves it somewhere and returns you the location of that file. Now, change the src tags to point to the local images, and call setText method on the TextView.
And that should do it. The important thing to remember is, you have to change the HTML to point it to the file that you have downloaded.
Sample Source code : http://code.google.com/p/myandroidwidgets/source/browse/#svn/trunk/TextViewHTML
This sample doesn't use threads. So, your UI will be blocked unitl the image here is downloaded. So, keep waiting. :)
Tuesday, June 8, 2010
Wednesday, June 2, 2010
Checking Network Availability
I have seen a few applications which first try to initiate a network connection before checking if any network is available or not. And then, if the request fails, they toast a message saying "No network available". This might not be the right approach in most of the situations. Before initiating a connection, we should always check the availability of a network and then proceed. Android provides a simple way by which you can know the status of the active network if any. So, why not use it. It's very simple.
The code:
The code:
public static boolean isNetworkAvailable(Context context) {
boolean value = false;
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
}
return value;
}
Thursday, April 8, 2010
Simple Drag n Drop on Android
Till now, there is no Drag and Drop like control on the Android. This feature might come in handy in a few situations to improve the usability of your apps. Here is a simple Drag and Drop app which allows you to drag a button and drop it anywhere on the screen.
Theory: Go for a FrameLayout.
FrameLayout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen. Children are drawn in a stack, with the most recently added child on top.
In our main layout, we have a single button. We write a touch listener which will track the touch events and also help us to move the button around the screen. In this example, we will not be moving the button, but it’s image which we set to a ImageView. Also, instead of actually moving the ImageView, we will change the padding of the ImageView as the mouse moves, which will give an impression of the ImageView being moved.

The source code for this can be found on this link.
Drag and Drop example
Theory: Go for a FrameLayout.
FrameLayout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen. Children are drawn in a stack, with the most recently added child on top.
In our main layout, we have a single button. We write a touch listener which will track the touch events and also help us to move the button around the screen. In this example, we will not be moving the button, but it’s image which we set to a ImageView. Also, instead of actually moving the ImageView, we will change the padding of the ImageView as the mouse moves, which will give an impression of the ImageView being moved.
The source code for this can be found on this link.
Drag and Drop example
Chapter:
Android,
Android Tricks,
drag drop,
UI
Monday, April 5, 2010
Custom ProgressBar for Android
We will try to make a new progress bar with our own progress animation. It's pretty simple and can be easily set up to run in few minutes. Here we go.
1. MyProgressBar.java
This class extends the ProgressBar class and has two methods that we would need to call to start and stop the animation.
To start the animation: call startAnimation()
To stop the animation: call dismiss()
Basically, we run a thread which keeps on switching the images. That's it.
2. myprogressbar.xml
This is the layout that the MyProgressBar would be using. This animation would be using 9 images which are in the drawable folder.

You can check out the whole project from the SVN. Here is the link.
https://myandroidwidgets.googlecode.com/svn/trunk/Custom_Progress_Bar
1. MyProgressBar.java
This class extends the ProgressBar class and has two methods that we would need to call to start and stop the animation.
To start the animation: call startAnimation()
To stop the animation: call dismiss()
Basically, we run a thread which keeps on switching the images. That's it.
2. myprogressbar.xml
This is the layout that the MyProgressBar would be using. This animation would be using 9 images which are in the drawable folder.

You can check out the whole project from the SVN. Here is the link.
https://myandroidwidgets.googlecode.com/svn/trunk/Custom_Progress_Bar
Chapter:
Custom Widgets,
Progress Bar,
UI
Sunday, April 4, 2010
Custom AutoComplete for Android
The default custom AutoCompleteTextView is quite a nice widget. But if you want to extend it's functionality, you will need to write your own custom widget. As an example, if you wish to have a EditText for a "To" address field as any email application has, where you want to collect multiple selections from the list that pops up, you will need to extend the AutoCompleteTextView class and write your own small little widget. It's very simple to create one that will suit your need.
So here we go.
1. Class CustomAutoComplete.java
This class is the main widget class that extends thet AutoCompleteTextView. You have to override 2 methods,
3. Now we test it. This is your activity class.
Voila, you are done. Here’s a screenshot of our Custom Auto-Complete Text view at work.
You can also change the separator from the default “;” to any other character like a “,” or anything else.
On the adapter, you call the method setSeparator(String any);
Now you have your own custom auto-complete widget for Android.
For this particular example, however, Android provides you a widget by default. MultiAutoCompleteTextView is specifically designed to handle such kind of input.
So here we go.
1. Class CustomAutoComplete.java
1: package com.beanie.example.widgets;
2: import android.content.Context;
3: import android.text.TextUtils;
4: import android.util.AttributeSet;
5: import android.widget.AutoCompleteTextView;
6:
7: public class CustomAutoComplete extends AutoCompleteTextView {
8: private String previous = "";
9: private String seperator = ";";
10: public CustomAutoComplete(final Context context, final AttributeSet attrs, final int defStyle) {
11: super(context, attrs, defStyle);
12: this.setThreshold(0);
13: }
14: public CustomAutoComplete(final Context context, final AttributeSet attrs) {
15: super(context, attrs);
16: this.setThreshold(0);
17: }
18: public CustomAutoComplete(final Context context) {
19: super(context);
20: this.setThreshold(0);
21: }
22: /**
23: * This method filters out the existing text till the separator
24: * and launched the filtering process again
25: */
26: @Override
27: protected void performFiltering(final CharSequence text, final int keyCode) {
28: String filterText = text.toString().trim();
29: previous = filterText.substring(0,filterText.lastIndexOf(getSeperator())+1);
30: filterText = filterText.substring(filterText.lastIndexOf(getSeperator()) + 1);
31: if(!TextUtils.isEmpty(filterText)){
32: super.performFiltering(filterText, keyCode);
33: }
34: }
35: /**
36: * After a selection, capture the new value and append to the existing
37: * text
38: */
39: @Override
40: protected void replaceText(final CharSequence text) {
41: super.replaceText(previous+text+getSeperator());
42: }
43: public String getSeperator() {
44: return seperator;
45: }
46: public void setSeperator(final String seperator) {
47: this.seperator = seperator;
48: }
49: }
protected void replaceText(final CharSequence text)
protected void performFiltering(final CharSequence text, final int keyCode)2. You main layout file (main.xml)
1: <?xml version="1.0" encoding="utf-8"?>
2: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3: android:orientation="vertical" android:layout_width="fill_parent"
4: android:layout_height="fill_parent">
5: <com.beanie.example.widgets.CustomAutoComplete android:layout_width="fill_parent"
6: android:layout_height="wrap_content" android:id="@+id/autocomplete"/>
7: </LinearLayout>
1: package com.beanie.example;
2: import android.app.Activity;
3: import android.os.Bundle;
4: import android.widget.ArrayAdapter;
5: import com.beanie.example.widgets.CustomAutoComplete;
6:
7: public class TestAutoComplete extends Activity {
8: /** Called when the activity is first created. */
9: @Override
10: public void onCreate(Bundle savedInstanceState) {
11: super.onCreate(savedInstanceState);
12: setContentView(R.layout.main);
13: CustomAutoComplete myAutoComplete = (CustomAutoComplete)findViewById(R.id.autocomplete);
14: ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
15:
16: adapter.add("aaaa");
17: adapter.add("abaa");
18: adapter.add("acaa");
19: adapter.add("adaa");
20: adapter.add("aaba");
21: adapter.add("aaca");
22: adapter.add("aaba");
23: adapter.add("aaae");
24:
25: myAutoComplete.setAdapter(adapter);
26: }
27: }
You can also change the separator from the default “;” to any other character like a “,” or anything else.
On the adapter, you call the method setSeparator(String any);
Now you have your own custom auto-complete widget for Android.
For this particular example, however, Android provides you a widget by default. MultiAutoCompleteTextView is specifically designed to handle such kind of input.
Chapter:
Android Hacks,
Custom Widgets,
UI,
Widgets
Subscribe to:
Posts (Atom)
