Tuesday, April 26, 2016

Android Kotlin with Anko

I recently found an interest in Android, this time with Kotlin and Anko. Kotlin is an alternative language to build Android App and it's a more modern language therefore it has its own advantage and possibly cleaner way to program then Java. Jetbrains made an amazing job with IntelliJ in making sure that you can create Android Apps. Having said that, here is a tutorial on how to start your first Kotlin Android App. Getting started with Android and Kotlin.

Incase you encounter an error, open your app's build.gradle and replace the contents with the generated content from kotlin build.gradle generator. Note that this has anko in its dependencies.

So what is Anko? From its github page Anko is a library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of Android SDK for Java. It's mostly known for its DSL for making UI but there are few view related extensions that are quite helpful in developing new apps.

Let's see how Kotlin and Anko works. Here is an example of a sharing fragment class
class ShareFragment: Fragment() {
    companion object {
        val FACEBOOK_URL = "https://m.facebook.com/pages/somePage"
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
 savedInstanceState: Bundle?): View? {
        return UI {
            linearLayout {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER_HORIZONTAL

                textView("Share to FB")

                imageButton {
                    imageResource = R.drawable.facebook
                    onClick {
                        owner.gotoUrl(FACEBOOK_URL)
                    }
                }

                textView("Sharing to other network will appear later")
            }
        }.view
    }
}

Just reading from the UI part you would know that this is a linearLayout with gravity horizontally centered and its children is stacked vertically. The first child is textView with text Share to FB, below it is an imageButton with resource drawable named facebook. Then below it is also a textView with the text Sharing to other network.

owner.gotoUrl(FACEBOOK_URL);
You might be wondering what is this, this is called extensions. In kotlin, you can extend base class with your custom functions. With this specific code the owner is a Fragment. So i would have a code like
fun Fragment.gotoUrl(url: String) {
    val intent: Intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(intent)
}

The advantage of doing this is that if you decided to put a share button in another fragment you wont have to duplicate the code. Kotlin advices to use this approach then using an utility based approach. And for me, this way is a lot cleaner.

You could put the Fragment.gotoUrl at the end of the class or a more organised approach is to create an class with all your view related extensions, i called mine ViewExtensions.kt. Here is a gist.

I have just started to learn kotlin and I found it to be interesting. Hope this helps :)

Wednesday, December 9, 2015

Android Links 2

Another round of Android links :)

1) Developing for Android: the Naughty Bits (Android Dev Summit 2015)

Last week i featured the article from medium (Developing for Android: Introduction), during Android Dev, Chet Haase and Romain Guy talks some aspect about it.

2) Android Studio for Experts- Cheat Sheet

Another one from Android Dev Summit, this time its Android Studio, @shem made a really nice cheat sheet based from the video.

3) AdMob integration in Android
If you need to use ads on your app and you want to use AdMob, then this blog shows you how to implement it from downloading dependencies in using sdk manager to including it on your group view. It shows how to implement code for both banner ads and interstial ads.

4) What’s in a web browser
This is about the web browser in Android, from the early days of Android to why it was super seeded by Chrome codebase on Android 4.3. It is a good read specially if you are developing a web app and/or want to know what's happening behind the browser.

Sunday, December 6, 2015

Android Links 1

Today i would start a new trend to keep this blog alive, i wont be blogging as currently I'm not doing Android related but I would showcase 3 Android reads/sites/videos that could help developers with their android app.
Here are the first 3, enjoy :)

1) Developing for Android: Introduction
This is more of rules to developing im Android then an introduction, however it is essential to read it as it writes about why some Android behaves different between versions and what we can do for our app.

2) Google developer youtube
There are tons of videos that takes about how to develop on android.

3) Advanced Android Espresso
Video about testing in Android with espresso, it is from the recent AnDevCon.

Monday, May 4, 2015

Dart and Android

It's time to learn new language now that the future seems to be Android and Dart. Here is the video


Sunday, March 15, 2015

Extending Components and AppTheme with Material Design

Recently I have been dealing with custom font in the default components of Android. However I need to use different fonts in English and one font in Chinese. As we know integrating custom fonts with the default components shipped out by Android is a bit tricky specially if you have to cater earlier version of the platform. To fix this problem, i need to extend the components first and this StackOverflow post helped with setting up the classes.

Another piece of the puzzle is with making it use the widget tinting that comes with appcompat v21. We need this because without it we need to generate a lot of files (drawable, styles, etc) and maintaining them is not fun. For this, we refer to the appcompat v21 material design for pre lollipop where we just need to put colorAccent, colorControlNormal, colorControlActivated, colorControlHighlight & colorSwitchThumbNormal. But then, our problem is that if we extend RadioButton, EditText and others, the tinting is not applied. Initially I extended the style of the RadioButton to android:Widget.CompoundButton but nothing happens, then I make sure that if I just use RadioButton and set the color* that it would work and it did. After few tries, I went back to StackOverflow and found this in where it tells use to extends the internal class.

So I made an experiment and here is the gist
First, we create a FontUtils so that we could reuse it with different components
public class FontUtils {
    public static int FONT_REGULAR = 0;
    public static int FONT_THIN = 1;

    public static void setTypeface (int fontName, TextView textView) {
        Typeface font = null;
        Context context = textView.getContext();
        Resources resources = context.getResources();
        if (fontName == FontUtils.FONT_REGULAR) {
            font = Typeface.createFromAsset(context.getAssets(), resources.getString(R.string.font_regular));
        } else if (fontName == FontUtils.FONT_THIN) {
            font = Typeface.createFromAsset(context.getAssets(), resources.getString(R.string.font_thin));
        }
        textView.setTypeface(font);
    }
}

The full class is here, basically here we create a helper class that would set the typeface based on the fontName that is passed from the xml. We create the typeface from the files we have under assets/ using the Typeface.createFromAsset(context.getAssets(), resources.getString(R.string.font_thin)); where the getString() will load the path of the string based on the locale we have. For example we passed in 0 (FONT_REGULAR) we would then load fonts/Roboto-Regular.ttf for English and fonts/NotoSansCJKtc-Bold.oft for Chinese.

For the custom class we have RadioButton as example but it could easily be done with EditText, CheckBox, Spinner using the prefix Tint.
public class RadioButtonCustomFont  extends TintRadioButton {
    private int mFontName;
 
    ...
    public RadioButtonCustomFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }
    ... 

    private void init(AttributeSet attrs, int defStyle) {
        final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.font, defStyle, 0);
        mFontName = a.getInt(R.styleable.font_name, FontUtils.FONT_REGULAR);
        a.recycle();
 
        if (!isInEditMode()) {
            FontUtils.setTypeface(mFontName, this);
        }
    }
}

Here we just pass the mFontName to our FontUtils helper, we got that from the xml on our layout.

To create our RadioButtonCustomFont on our layout we must do something like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:font="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.monmonja.tutorial.RadioButtonCustomFont
        font:name="Regular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Yes"
        />
</RelativeLayout>

Here we create a namespace for font (the same as the name in our assets.xml) then we pass in font:name the value/s from the assets.xml.

Finally we need to apply the tinting that comes with appcompat, for that take a look at the our themes.xml and its explanation is the same as Appcompat for pre-lollipop theming part
Hope this helps :)