Android ViewPager Cube Animation

After trying some libraries in order to make a cube animation for my viewPager, I realized that is pretty easy to do this. Android provides an interface called ViewPager.PageTransformer and you just have to implement its method transformPage().

Below is the code, step by step.

activity_main.xml

view_pager_item.xml

 

And now, the interesting part of the tutorial:

CubeTransformer.java class

Let’s explain a bit this code. As you can see, we created a new class CubeTransformer that implements the interface I mentioned at the beginning of the post, ViewPager.PageTransformer. The tranformPage() method that has to be overridden, is called for each visible page and for its adjacent pages (left and right) and requires a view and position.

  • view: represents either the current view that starts beeing swiped, either the next one
  • position: represents either the position of the current view, either of the next one
    • 0 – is for the current view/page when it fills the screen
    • 1 – is for next view/page that has just been drawn
    • when the user starts to swipe between pages, page one (current) will have positions with negative values, and the next page that has to come in place, will have positions with positive values.

Before going further, we have to mention that in Android the x,y coordinates start from the top left corner.

The animation is done with just 3 lines of code:

  • view.setPivotX(): This is like a pin on the x axis around which the view will be rotated and scaled.

In our code, when position <= 0 (current image) we will set the pivot on the rightmost point of the X axis (view.getWidth()) , and when position > 0, (next image) the pivot is set on the left (origin of the axis) on X axis. This way, the pages will look like the faces of a cube.

  • view.setPivotY(): This is like a pin on the Y axis, around which the view will be rotated and scaled.

In our code, we set this to be on the halfway on Y axis.

  • view.setRotationY(): The view will be rotated vertically around Y axis with 90 degrees on the left multiplied by position.

So, using these 3 lines of code, we can have a cube animation on our viewPager 🙂

Now, the final step of the tutorial, is about how to use the above class.

MainActivity.java

The only new thing in the above code, is this line:

The rest of the code is just the usual implementation of a ViewPager.

Android – HTML in textView

Display HTML format

First we will present below what are the supported tags for a textView and what are not supported. You can skip this section if you are already familiar with these or you want to jump directly into action 🙂

Supported tags
Unsupported tags
  • <a href=”…”>
  • <b>
  • <big>
  • <blockquote>
  • <br>
  • <cite>
  • <del>
  • <dfn>
  • <div align=”…”>
  • <em>
  • <font size=”…” color=”…” face=”…”> Size is working only for strings in strings.xml, for strings in Java code it seems that size DOESN’T change. Face is working in both xml and java code but only for default faces that Android supports like (monospace, serif, etc)
  • <h1>
  • <h2>
  • <h3>
  • <h4>
  • <h5>
  • <h6>
  • <i>
  • <img src=”…”>
  • <li>
  • <p>
  • <s>
  • <small>
  • <strike>
  • <strong>
  • <sub>
  • <sup>
  • <tt>
  • <u>

 

  • <abbr>
  • <acronym>
  • <address>
  • <area>
  • <article>
  • <aside>
  • <audio>
  • <base>
  • <basefont>
  • <bdi>
  • <bdo>
  • <body>
  • <button>
  • <canvas>
  • <caption>
  • <center>
  • <code>
  • <col>
  • <colgroup>
  • <data>
  • <datalist>
  • <dd>
  • <div>
  • <dl>
  • <dt>
  • <details>
  • <dialog>
  • <dir>
  • <embed>
  • <fieldset>
  • <figcaption>
  • <figure>
  • <font size…>????? doesn’t work for strings declared in Java code.
  • <footer>
  • <frame>
  • <frameset>
  • <form>
  • <head>
  • <header>
  • <hr>
  • <html>
  • <iframe>
  • <input>
  • <ins>
  • <kbd>
  • <label>

 

  • <legend>
  • <link>
  • <main>
  • <map>
  • <mark>
  • <menu>
  • <menuitem>
  • <meta>
  • <meter>
  • <nav>
  • <noframes>
  • <noscript>
  • <object>
  • <ol>
  • <optgroup>
  • <option>
  • <output>
  • <param>
  • <picture>
  • <pre>
  • <progress>
  • <q>
  • <rp>
  • <rt>
  • <ruby>
  • <samp>
  • <script>
  • <section>
  • <select>
  • <source>
  • <span style=””>
  • <style>
  • <summary>
  • <table>
  • <tbody>
  • <td>
  • <textarea>
  • <tfoot>
  • <th>
  • <thead>
  • <time>
  • <title>
  • <tr>
  • <track>
  • <ul>
  • <var>
  • <video>
  • <wbr>

 

1. String in Java code

Examples that don’t work

  • Using alpha channel

Note: 80 from #800000FF should have added a blue color with an alpha of 50% to the “blue” text

Examples that work

  • Using rgb

  • Using hexa (it works with lower case letters also)

2. String in strings.xml

When the text that needs to be formatted is located in strings.xml, there are a few ways of getting the text. Unfortunately, not all of them will keep the style.

strings.xml

Examples that DON’T work

  • using getString()

  • using getString() + Html.fromHtml()

 Examples that work

  • using getText()

  • using the resource id directly

  • Using getString() + Html.fromHtml()+<![CDATA[html source code]]>

<![CDATA[html source code]]> is used in strings.xml so that you can use the actual HTML you include without needing to translate all the special characters like <, >, etc.

Note: CDATA is working only if the string is retrieved using Html.fromHtml().

Note 2: Also notice that when we used CDATA color=red is written without ”. If you keep ” they need to be escaped.

What is the difference between getText() and getString()?

  • getText() returns CharSequence
  • getString() returns String

Below is a table in which are presented CharSequence interface and some of the classes that implement this interface.

As you could see from the above table, String objects do not keep style formatting, so this is why calling getString() won’t work. On the other hand, getText() internally uses Html.fromHtml() to parse HTML tags, which returns a Spanned object, which keeps the style formatting of a text.

  • alpha channel

As you can see, the transparency is working for strings declared in strings.xml. For now, I am not sure why it’s working for xml but not for java code. If you know or find an answer please post a comment on the post.

 

 

 

Conclusion

For strings located in strings.xml file use:

textView.setText(getText(R.string.formatted_text));

And for strings in Java code use:

textView.setText(Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT));

3. General examples

Other motives that might not keep the style on a text:

 

 

 

Resources:

https://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html

http://saket.me/html-tags-textview/?utm_source=Android+Weekly&utm_campaign=4fc49af2d9-android-weekly-265&utm_medium=email&utm_term=0_4eb677ad19-4fc49af2d9-337918897

 

Kotlin – How to pass function as parameter

Recently, I’ve noticed that there are a few different ways to pass a function as parameter. In this post I will use 2 functions: sum and divide. We have to declare the sum function, in such way that it can receive the divide function as argument.

The most common and often more convenient (according to Kotlin documentation) is to pass a lambda expression.

1. Pass a lambda expression

In order to make the sum function to accept a function passed as lambda expression, we have to declare the 3rd parameter c as a lambda.

  • lambda expression with no parameters

  • lambda expression with 2 parameters

  • pass lambda expression directly without divide method

 

2. Use :: operator

As you can see, the signature for the 3rd param from sum function also changed. As we do not pass a function as lambda, we declare the c parameter as a “normal” Int.

Also, notice how we had to reference the divide function in this case. We had to specify the context (the class in which the function was declared), and the arguments were declared separately inside other parenthesis.

Specifying the context was necessary because the functions are declared in a class. Only if we write the functions directly in a Kotlin file (NOT inside a class) we can call directly ::divide. See the example below:

Functions in Kotlin

In this post I will talk about 5 cool things that functions can do in Kotlin, better than methods in Java.

  1. Forget about overloaded methods

In Java, when you need the same method to have 1 parameter in one case and more parameters in another case, you would have to overload the method. This means to write another method with the same name, but different parameters. In Kotlin, this is history. You can provide default values for parameters, which are used when you do not provide all the corresponding arguments.

  • Java

    Kotlin

     

2. A function can have as a parameter another function

A function that takes another function as parameter is called Higher-Order function.

3. We can create a function inside another function

A function that is created inside another function is called local function.

4. We can create functions without name

A function that does NOT have a name, is called an anonymous function

5. We can use lambdas

A lambda function is a simpler way of representing an anonymous function.

 

Anonymous Functions and Lambdas – Kotlin

Note! This is a post for beginners in Kotlin language.

What are lambdas and anonymous functions? In order to define them let’s see what is a function literal.

Function literal

Function literal is a function that was not declared, but was passed as an expression.

What functions are ‘function literal’?

The following are called ‘function literal’:

  • lambda expressions
  • anonymous functions

Lambda Expressions

Full syntax:

Pass lambda as a parameter to a function with more parameters

NOTE: The equivalent syntax for sum function is:

Let’s do some analysis on this function. It requires the first 2 parameters to be of type int, and the last one as a lambda expression. The lambda expression requires 2 parameters of type int (a, b) and returns an int.

So far, so good. The sum function must return an int also, so when we return lambda (c(a,b)) we actually return an int value in the end.

Also, as you can see, when we want to return a lambda we have to use parentheses with parameters, when they exist. When there is no parameter, then we write only empty parentheses.

Pass lambda to a function that has only the lambda function as parameter

Also the equivalent syntax for one function is:

Overview

  • lambdas are always surrounded by curly braces ‘{}’
  • parameters are defined before “->” symbol
  • the body (what your method should return) is defined after “->” symbol
  • if a function has:
  • more parameters and the last parameter of a function is a lambda expression, then the lambda expression can go outside the parentheses
  • only one parameter and the last parameter is a lambda expression, then we can write the lambda expression without parentheses
  • if we have only one parameter in a lambda expression, and we do not use it, we can omit itwhen a lambda has only one parameter and Kotlin can figure the signature out itself, we do not have to declare that parameter. Kotlin will declare it for us under the name “it”
  • return inside an lambda expression will return from the enclosing function

Anonymous functions

As a block:

As an expression:

Overview

  • Anonymous functions are like regular functions, but without a name
  • parameter types can be omitted if they can be inferred from context
  • parameters are always passed inside the parentheses. If the last parameter of a function is an anonymous function, the anonymous function cannot go outside the parentheses (this works only for lambdas)!
  • return inside an anonymous function will return from the anonymous function itself

You can learn more from https://kotlinlang.org/docs/reference/lambdas.html#lambda-expressions-and-anonymous-functions

Introduction to Functions – Kotlin

In this post, I will try to explain how to write functions in Kotlin by doing a parallel with Java. It’s not rocket science or anything special in this post, but this is the way I understand and remember better how to write in Kotlin, myself (it’s something new to me too 🙂 ), so maybe this post will help others too.

Defining functions

Kotlin

Java

 

Writing function/method declaration analysis

  • in both Kotlin and Java, we start writing with the access/visibility modifier “private”Note! In Kotlin, we do not have to write the visibility modifier “public“. It can be omitted, regarding that is the default visibility when no explicit modifier is provided.
  • next, in Kotlin we have to use the “fun” keyword, in order to specify that it is a function. Instead, in Java, we have to write the return type of the method/function.
  • next, in both languages we have to write the name of the method/function
  • after the name, we have to write parameters between “()” in both languages. The differences appear in writing the parameters. In Java we wrote the type and then the name of the param (int a), whereas in Kotlin we have to write the name first, “:” and then the type (a: Int). Note that the int type in Kotlin starts with capital i (Int). If there are more parameters, they are separated with “,” (in Java and Kotlin).
  • next, in Java we would open “{“, but in Kotlin, we have to add “:” and then the return type of the function, and only after that we would open “{” ( (a: Int, b: Int): Int { ). So, the return type in Java is written at the beginning, and in Kotlin at the end of the function/method declaration. NOTE: When there is no return type: in Java we use void, whereas in Kotlin we use Unit (or we can omit writing Unit).
  • next, in the body of the method we write the code we need (in this example a sum of a + b). Notice that in Java we MUST add “;” at the end of sum expression (return a + b;), whereas in Kotlin, is not a must. You can add it, but is redundant.

 

Java Kotlin
private private
int fun
sum sum
( (
int a, int b a: Int, b: Int
) )
{ :
return a + b; Int
} {
return a + b
}

Syntax

Kotlin

visibility fun name(paramName1: type, paramName2: type): returnType {

        expresion

}

Java

visibility returnType name(type paramName1, type paramName2) {

       expresion;

}

Shorter way of writing the above method in Kotlin

This is called a function with an expression body and inferred return type. Inferred type means that the compiler deduced the return type of the expression, so we don’t have to write it explicitly. I like this pretty much as it looks clean and easy to read.

Function returning nothing (in Java, void)

Or

You can learn more at http://kotlinlang.org/docs/reference/basic-syntax.html

Kotlin – Hello world

Introduction

What is Kotlin?

It is a new programming language built by JetBrains, and as you may already know, Google announced at Google I/O 2017, that they will now officially support this language. It is inspired by existing languages such as Java, C#, JavaScript, Scala and Groovy.

What are the advantages of using Kotlin?

  • it’s a more concise language (40% cut in the number of lines of code)
  • less NullPointerException errors by making all types non-nullable by default
  • New features like:
    • smart casting
    • high order functions
    • Coroutines
    • Lambdas, etc

Hello World, Kotlin

Let’s create a Hello World project. Create a new project by checking Kotlin option that is available starting with Android Studio 3.0 (Note! If you already have a project and want to convert it to Kotlin, Android Studio has an option to do this too, but we will talk about it in another post).

Step 1

File – New – New Project

Step 2

Step 3

Step 4

Step 5

Step 6

Notice that a kotlin-android plugin was added to the module gradle file.

Step 7

Also, notice these changes in the project build.gradle file.

activity_main.xml

MainActivity

Now, in the MainActivity class, the onCreate() method, looks like this:

As you can see there are changes in the writing (obviously :P):

  • instead of “MainActivity extends AppCompatActivity” now we have to use “:
  • onCreate is now a function
  • the onCreate parameters look like this now “savedInstanceState: Bundle?” (we will get more into this in other posts)

COOL FACT: Notice that we could set a text on our TextView without using findViewById()! We just wrote the id itself and set the text and that’s it. Cool, ha? 🙂

How to get current flavor from gradle

 Figuring out how to pull the current flavor from gradle

While working on an update for one of our games, I needed to figure out how to get the current flavor and use it in code. Since there are a lot of ways to do this, I chose to create a custom build config parameter and set the value in each variant I have.

Adding a new build config field

First thing is to add a new build config property in your flavors. Using buildConfigField helps us do that. Therefore I defined a String called VARIANT and set the value to paid or free depending on what flavors I have.

Just in case you don’t know where productFlavors should be put, it is inside the android definition of your build.gradle.

By doing this you can access that value in your code using the BuildConfig class that is generated by Gradle. You can use the same class to check if the current build is in debug/release mode or other stuff.

Get the current flavor name

Now, to access the newly created property and use it I do something like this:

Conclusions

I use this approach because it gives me the power to name the flavors to whatever I want. I also feel that is less hacky than looping through different directories or figuring out paths to get the flavor and in the end if the flavor name gets changed maybe I will forget to change it in the code as well..

Probably there are a lot more ways to get to the same thing but this feels to me that is a viable solution :). I am curious to see other ways to do the same thing from others. Please post your own solution in the comments below. Thanks!

 

 

 

Signing key SHA1 fingerprints within AndroidStudio

Did you know you can get the signing SHA1 and MD5 fingerprints within AndroidStudio?

If you need the SHA1 or MD5 fingerprints of your Android debug/release key/certificate for a new API or framework that you want to integrate in your project like Firebase or Maps, then you can also get it from AndroidStudio.

Follow the steps below to get your SHA1 or MD5 fingerprint of your key/certificate:

  • Open your project in AndroidStudio
  • Go to the Gradle tab on the right side of the IDE
  • Expand yout project and go to Tasks->Android->signingReport
  • Double click signingReport
  • Below in the Run tab you will see the output where you can also find the fingerprints for each signing configuration your have

You can see the same steps in the picture below.

Android signing key SHA1 & MD5 AndroidStudio
Android signing key SHA1 & MD5 AndroidStudio