Android Addicted Apps Creator

September 11, 2012

Make Activity using Theme.Dialog fill the entire screen

Filed under: Tips — alinberce @ 07:55
Tags: , , ,

   Admitted, you hate using AlertDialog for complex layouts that contain many controls. I hate it, it makes me feel so limited. Of course it has its own advantages, let’s not be mean, but sometimes a new Activity unleashes the power within.

So, how do we make an Activity look like a dialog ? Simple, just add in manifest:

 <activity
            android:name=".MyDialogActivity"
             android:theme="@android:style/Theme.Dialog" />

    But the problem is, even if we set our layout properties, to fill_screen, the activity will wrap around the content and its size will vary of the info. I thought, if the xml setting is ignored, maybe setting it in code might work… and surprise, it does work. All you have to do is:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.my_dialog_layout);

    //after setContentView, set the Layout parameters to fill parent, this makes our activity to go full screen
    getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}

February 20, 2012

Android EditText with custom font and clear button

Filed under: Android — alinberce @ 20:22
Tags: , , , , , ,

C’mon, admit it, you’ve always wanted this. Have you ever felt that text clearing in your android application on EditTexts feels… wrong ?

So, what do we want to achive?

Plain and simple, a TextView, based on the same principle as the previous TextView tutorial, with custom fonts (from assets folder) and with a Clear button.

image

Proceed with caution…

  Of course, if you get a request to use custom fonts in you app, this does not apply only to TextViews, but to all items like Buttons, List Items and EditTexts.

First we need to create our own custom control, extending EditText and adding the following:

  • an image resource for the Clear button
  • an TextChangedListener so we only show the Clear button when the EditText contains something
  • method for setting our custom TypeFace
  • TouchListener so we detect if the user taped on the Clear button area.

Our project will contain a few things:

image

  1. Main activity: AndroidTutorialActivity.java
  2. Our custom control: MyEditText
  3. Custom fonts in assets folder
  4. Clear_button_image resource for the button  image
  5. Main.xml as the main layout.

I’ll just post the entire code with comments and I’m sure you’ll understand it in a second:

public class MyEditText extends EditText{

	//The image we are going to use for the Clear button
	private Drawable imgCloseButton = getResources().getDrawable(R.drawable.clear_button_image);
	
	public MyEditText(Context context) {
		super(context);
		init();
	}

	public MyEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	void init() {
		
		// Set bounds of the Clear button so it will look ok
		imgCloseButton.setBounds(0, 0, imgCloseButton.getIntrinsicWidth(), imgCloseButton.getIntrinsicHeight());

		// There may be initial text in the field, so we may need to display the  button
		handleClearButton();

		//if the Close image is displayed and the user remove his finger from the button, clear it. Otherwise do nothing
		this.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				MyEditText et = MyEditText.this;

				if (et.getCompoundDrawables()[2] == null)
					return false;
				
				if (event.getAction() != MotionEvent.ACTION_UP)
					return false;
				
				if (event.getX() > et.getWidth() - et.getPaddingRight() - imgCloseButton.getIntrinsicWidth()) {
					et.setText("");
					MyEditText.this.handleClearButton();
				}
				return false;
			}
		});

		//if text changes, take care of the button
		this.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				MyEditText.this.handleClearButton();
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
		});
	}
	
	//intercept Typeface change and set it with our custom font
    public void setTypeface(Typeface tf, int style) {
	    if (style == Typeface.BOLD) {
	        super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-B 0.602.otf"));
	    } else {
	        super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-R 0.602.otf"));
	    }
    }
	
	void handleClearButton() {
		if (this.getText().toString().equals(""))
		{
			// add the clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], null, this.getCompoundDrawables()[3]);
		}
		else
		{
			//remove clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], imgCloseButton, this.getCompoundDrawables()[3]);
		}
	}
}

Don’t forget to add it in your main layout

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.alinberce.app.MyEditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="My cool edit text" />
</LinearLayout>

Run it and see the result:

 

image

Source code of the project can be found: HERE

image

Are They Dead ?

Filed under: Android — alinberce @ 20:08
Tags: , , , , , , ,

Are They Dead – It’s not just an app, it’s a matter of Life & Death

image

Have you ever caught yourself wondering "Hey, are they still alive?" Well ‘Are They Dead?’ let’s you easily search for your favorite celebrities and answer that very question.

  • -View information on your favorite celebrities, including their age, birthday, the date they died and cause of death.
  • -Can’t remember the persons name? Search from films, TV shows and even bands!
  • -Search by a specific date. Find out who might have died on your birthday, or which celebrity has the same birthday as you.
  • -Search from millions of entries!
  • *(Coming Soon) Notifications! Keep track of your favorite celebrities and get notifications on their birthday, status, or the anniversary of their death. Completely customizable. Plus many more features!

 

  

 

image https://market.android.com/details?id=com.aretheydead.app

Technical details

Application uses:

  • Freebase querying via MQL language
  • JSON data parsing
  • HTTP calls
  • Custom controls with user TypeFace
  • AsyncTasks
  • Async image fetching
  • Neat Auto search with suggestions list Winking smile

January 25, 2012

Using custom fonts in android. Bold, Italic, Regular… you name it!

Filed under: Android — alinberce @ 18:22
Tags: , , , , , , ,

As time has proven me, in Android many of the things I was used to make quite easy in .net, require a lot of manual coding. Using custom fonts does not make an exception… Everything depends on what you/your client wants to have in the app.

Brief intro regarding fonts.

First take a very good look at the font license. Of course, the best fonts, the handsome and good looking ones forbid free distribution. So in case you don’t want to have any legal issues, read carefully before using a certain font. Usually fonts are of two types: OTF stands for OpenType Font and TTF stands for TrueType Font (you can take a look at http://www.differencebetween.net/technology/difference-between-ttf-and-otf/ to see the difference between them). From what I have read around the web, they say that Android supports better TTF and is recommended that in case you want to use OTF to convert it. Personally I tried the both formats and all displayed well, so it’s up to you what type to use.

Setting things up. Put your coffee on your right…

The brief was very boring I know, but it was necessary. Now let’s settle our development environment. First, we need to use a free font. I have searched for an alternative to well known Myrian Pro from Adobe and recommendations went to Vegur. You can download it from: http://www.fontspace.com/arro/vegur . Please download the archive and take a look at it…

image

What in the name of God are those names you may say (as I did). That is the font indeed, but it is split into different files. So you’ve got Vegur-B 0.602 for Bold font, Vegur-R 0.602 for regular font and so on. When you create a project for android in Eclipse, you will see a folder called assets, make in assets new folder fonts and copy these two files in it and we’re done, fonts are added in our project. So simple, eh ?

image

How on earth do I use this font in my code ?

Let’s take a quick look at how a TextView is defined in an xml file.

<TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Regular TextView no typeface"
          android:textColor="#00FF00" />

<TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Regular TextView Monospace typeface"
          android:textColor="#00FF00"
          android:typeface="monospace" />

First TextView is plain and uses the default typeface. In the second TextView things are getting a bit complex as we have android:typeface attribute set to monospace. What does this mean ? The TextView will use Monospace font to display the text. Running the app will result in this:

image

I know what you are thinking… I’ll just replace monospace with my Vegur and we are done. Well, well, well… sorry to disappoint you, but there is no way we could use our custom font as a typeface straight from xml declaration. This is not cool. So all you code writing lovers, gather around as we need to dive into the wonderful world of custom controls.

Depending on your request there are several ways to do things, so we’ll take a good look and analyze/fix each one.

1.  I want a single TextView in my activity to use this font.

Maybe you have a logo text, or maybe you have some specific portion of text you need to make more obvious. In this case the solution is simple.

First add a new TextView in the main layout

<TextView
          android:id="@+id/txtOnlyOne"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="This TextView has our custom font"
          android:textColor="#00FF00" />

Go to main activity of the project, and within onCreate add this code:

Typeface tf = Typeface.createFromAsset(this.getAssets(), "fonts/Vegur-R 0.602.otf");
TextView tv = (TextView) findViewById(R.id.txtOnlyOne)
tv.setTypeface(tf);

image

Pretty simple and direct. We create the typeface in code and assign it to desired TextView. This may seem like a good solution in this case, but what if you face 20 TextViews ? It’s not so pleasant to find each one and assign the typeface to it. You could still try to do it this way, or you could go to next point…

2. I want the whoooooooooole activity to use this font.

Well, if setting it for a TextView was so simple…  setting it to all TextViews should be the same no ? The only thing that may give us trouble, is finding all the TextViews… so, why shouldn’t we look in all views and check? Take a look at this method:

private void overrideFonts(final Context context, final View v) {
      try {
        if (v instanceof ViewGroup) {
          ViewGroup vg = (ViewGroup) v;
         
			 for (int i = 0; i < vg.getChildCount(); i++) {
           	 View child = vg.getChildAt(i);
           	 overrideFonts(context, child);
         		 }

        } else if (v instanceof TextView ) {
          ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Vegur-R 0.602.otf"));
        }

      } catch (Exception e) {
      }
    }

Simply add this line, on activity after setContentView and see the results:

  overrideFonts(this, findViewById(android.R.id.content));

image

Wow… all TextViews look the same way, using our custom font. Good job. We should be fine, let’s go home and celebrate. But hey, what if…

3. I want the first and third TextView with bold font

Ah, piece of cake, I’ll just add android:textStyle="bold" for them and everything should be fine. Run and see the results

image

Ups… what da’… no change, it still looks the same way, where is my bold setting gone?

And now we get back to intro where we say that font file is split into several files. We need somehow to make sure that our TextView considers the textStype attribute and acts according to it. The only way to achieve this goal, in a nice manner, is to create a custom TextView and handle our typeface change in it. To keep things short, as I see you are bored, here is our extended control:

public class MyTextView extends TextView {

      public MyTextView(Context context, AttributeSet attrs, int defStyle) {
          super(context, attrs, defStyle);
      }

     public MyTextView(Context context, AttributeSet attrs) {
          super(context, attrs);
      }

     public MyTextView(Context context) {
          super(context);
     }


     public void setTypeface(Typeface tf, int style) {
           if (style == Typeface.BOLD) {
                super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-B 0.602.otf")/*, -1*/);
            } else {
               super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-R 0.602.otf")/*, -1*/);
            }
      }
 }

As you can see we intercept the setTypeface method, and depending of style value we assign our own custom typeface. To use it, simply add it in xml file

<com.alinberce.MyTextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="This MyTextView has our custom font"
         android:textColor="#00FF00" />

<com.alinberce.MyTextView
         android:id="@+id/txtOnlyOne"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="This MyTextView has our custom BOLD font"
         android:textStyle="bold"
         android:textColor="#00FF00" />

And finally we see it running and displaying the results as we wanted.

image

I personally use this as I don’t want to agglomerate my Activity code and allow me an easy way of changing the font for my entire app. You can simply put the "fonts/Vegur-B 0.602.otf" in a constant or a SharedPreference and when you change it, all you app will look different.

This post represents a resume of my questions on stackoverflow or answer found there. I just wanted to sum everything up and offer nuances of solutions based on everyone’s needs. I really hope you’ve understood it and will help you in the future. Please drop a comment if you liked it, or correct if I said something wrong.

You can find the source code of the article in this eclipse project : http://ifile.it/p0ovny3/FontsTutorial.src.zip

image

LATER EDIT: As time has proven me once again, Android is full of surprises. Using this font on Froyo/Gingerbread worked superb but on ICS… was rendered badly. The fix was quite easy: convert the OTF file to TTF using a free online font converter. Using the same font, but with TTF extension made the app look the same on all versions of Android. So kids, remember… Hate OTF, love TTF.

Compass VO for Android

Filed under: Android — alinberce @ 17:37
Tags: , , , , , ,

 

image

All you orienteering fans, gather around, I have a great announcement for you. Not an orienteering fan? No problem, after trying Compass VO along with Virtual Orienteering for Android you will be. I know what you were thinking when saw the app name “Oh boy, not another compass application”. The Android Market is full of compass applications, each having nice features and options. So, why a new one? That’s what I’ve asked the creators of the concept behind Compass VO. The answer is simple: it has some pretty neat features not found on other products that you’ll enjoy at max.

What makes Compass VO worth to try?

  • Use the popular 1, 2, 3 compass system along with this digital compass, the same as a real compass.
  • You can easily use an image of a map as a background. The image can be taken either from the phone’s Gallery or live with in-app integrated camera preview. But this is not all, after loading the map image you can manipulate it to suit your needs: rotate, zoom in and out, pan, everything is at your finger. The background remains saved and you can always update it, even after application is reopened.

image

  • Uses internal magnetic field and accelerometer sensor combined with GPS and wireless networks to offer accurate information. This allows you to choose if you want to use the magnetic heading or the true heading. All received information is available, depending on chosen theme.

image

  • Compass dial for target bearing and/or orienteering.

image

  • Multiple themes (Orienteering, Digital, Compass Rose, Mango graphics, Night, Android, many to come in the future) for each user’s taste, maybe you like a light theme or maybe a darker one… or why not the special Green robot theme

imageimageimage

  • No annoying ads, no pop-ups, no interruptions, no user spying.

I tried to keep permissions as few as possible. As you will see no “suspect” permissions like access your personal data or internet connection. So the ones that are needed are as follows:
Camera: used only on your request, with preview in order to take a photo of a map
Access fine location: used to calculate the Geographic North and offer Magnetic declination.
Wake lock: used to keep the screen on all the time. This is an option in Settings, but keep in mind that it uses a lot of battery.

      As a side note, please keep in mind that the accuracy of magnetic sensors in android powered devices is very variable. Based from manufacturer to manufacturer this can vary from pretty good accuracy to an unreliable one. You can always try to calibrate by holding the phone in front of you and moving it in a Figure-8 pattern, to see if it improves.

    Are you convinced to give it a try ? I sure hope so. Please take a look at About page in Settings. You can rate it in Android Market (5 stars please  ) or if you encounter any problems drop us an email and will do our best go fix it as fast as possible.
In the end, I must say I really enjoy working with the professional team from Just Windows Phone. Compass VO was made originally for Windows Phone Mango, carefully designed and implemented by them, and then ported by me on Android platform. I bet you wondered from what comes VO in the title? From Virtual Orienteering, this is the father project, Compass VO being a free tool to complete it. I invite you to also take a look at Virtual Orienteering community and the android application from the market.

Special thanks to:
 Virtual Orienteering – Find your way! – www.vorienteering.com

image

Just Windows Phonehttp://www.just-windows-phone.com

image

google_play https://play.google.com/store/apps/details?id=com.vorienteering.compassvo