Nov 23, 2015

What’s New in Android Studio 1.5

Android Studio 1.5 is focused on delivering more stability, with most of the enhancements being made under the hood. It adds new lint checks, the ability to use short names when code-completing custom views, and the memory profiler can now help you detect some of the most commonly known causes of leaked activities.

Android Studio 1.5 is now available to download from the stable release channel.

Find out more from Android Developers Blog: http://goo.gl/oIbJHO

Nov 9, 2015

What is Cardboard

What is Cardboard and Virtual Reality. This video introduces Cardboard for developers and how to use a phone and a simple box of Cardboard to tap into a new type of immersion with virtual reality.

Watch more episodes of Cardboard here:
https://goo.gl/IAoGGs



Cardboard: How Cardboard Works

Nov 5, 2015

Google Play services 8.3

Google Play services 8.3 is now out enabling you to build better apps with new functionality for: Sign In, Fused Location Provider, App Invites, and the Wearable Data Layer APIs.

Android and Android Studio: Getting Started


Learn how to get started with Android and Android Studio in this short tutorial. It demontrates how to install Android Studio (Google’s official Android IDE) and create your first Android app. You’ll learn how to download the Java SDK, download and install Android Studio, create a new “Hello World” project, and run your app on an emulator and real Android device.

You’ll also learn a series of Protips from an Android app startup as they go through the process of developing their app in a highly stressful environment. With over 1 billion Android devices already activated, Android represents an incredible opportunity for developers. Installing Android Studio is your first step!

Download the Java Development Kit: http://goo.gl/zXjC
Download Android Studio: http://goo.gl/2qpr
Android USB Drivers for Windows: http://goo.gl/91Y8C

Once you’ve installed Android Studio, learn more about developing Android Apps using these resources:
Android Developer Documentation: http://goo.gl/km7ab
Developing Android Apps Udacity Online Training: https://goo.gl/u1pxZv
Android Design for Developers Udacity Online Training: https://goo.gl/7W2S28

Check out more music from the composer: www.terramonk.com

Oct 15, 2015

Interactive flip ImageView using ObjectAnimator

User touch on buttons to flip the ImageView forward/backward alternatively, around X-axis and Y-axis.


package com.example.androidflipview;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    Button buttonFlipX, buttonFlipY;
    ImageView imageView;
    boolean dirX = true;
    boolean dirY = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView)findViewById(R.id.image);
        buttonFlipX = (Button)findViewById(R.id.buttonflipX);
        buttonFlipY = (Button)findViewById(R.id.buttonflipY);

        buttonFlipX.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(dirX){
                    dirX = false;
                    buttonFlipX.setText("Flip X Backward");
                    ObjectAnimator flip = ObjectAnimator.ofFloat(imageView, "rotationX", 0f, 180f);
                    flip.setDuration(500);
                    flip.start();
                }else{
                    dirX = true;
                    buttonFlipX.setText("Flip X Forward");
                    ObjectAnimator flip = ObjectAnimator.ofFloat(imageView, "rotationX", 180f, 0f);
                    flip.setDuration(1000);
                    flip.start();
                }
            }
        });

        buttonFlipY.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(dirY){
                    dirY = false;
                    buttonFlipY.setText("Flip Y Backward");
                    ObjectAnimator flip = ObjectAnimator.ofFloat(imageView, "rotationY", 0f, 180f);
                    flip.setDuration(2000);
                    flip.start();
                }else{
                    dirY = true;
                    buttonFlipY.setText("Flip Y Forward");
                    ObjectAnimator flip = ObjectAnimator.ofFloat(imageView, "rotationY", 180f, 0f);
                    flip.setDuration(3000);
                    flip.start();
                }
            }
        });
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
a
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/buttonflipX"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flip X Forward" />
    <Button
        android:id="@+id/buttonflipY"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flip Y Forward" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher" />
</LinearLayout>


Sep 14, 2015

Get Started AdMob for Android in Android Studio

AdMob uses the Google Mobile Ads SDK. This guide will show you how to integrate the Google Mobile Ads SDK into a brand new app and use it to display a simple banner ad. It should take about thirty minutes to complete and will give you a good sense of how the SDK functions within an app. If you're new to Google Mobile Ads, this is a great place to start before moving on to more advanced examples.

https://developers.google.com/admob/android/quick-start


Sep 9, 2015

Android Asset Studio

Android Asset Studio is a set of web-based tools for generating graphics and other assets that would eventually be in an Android application's res/ directory.



See the source on GitHub.

Sep 4, 2015

Google Android Developers Channel in YouTube

The home for videos, demos, tutorials, interviews, and anything else related to Android development. Android Developers channel at Youtube: https://www.youtube.com/user/androiddevelopers

Aug 8, 2015

Re-using Bitmaps

In modern mobile applications, Bitmaps can account for a large amount of memory churn. Constantly loading thumbnails, user icons, and Emoji sets can provide your users with a steady stream of media, but it can also contribute to some HUGE pauses for garbage collection. 

In this video Colt McAnlis, and for temporally allocated bitmaps, there’s a handy trick that you absolutely should be using to escape these performance problems: Re-using bitmaps.

Every time you allocate a bitmap, you have to incur some overhead to allocate the objects from the heap, which is less than ideal if you’ve got a lot of bitmaps. Rather than banging on the heap for new objects each time, you can instead, reuse the memory that an existing bitmap has created, and load your image there.

The end result? Less memory churn from bitmaps.


Pre-scaling Bitmaps

For media rich applications, BITMAPS are everywhere. But these high-resolution images can cause a horde of performance problems if the size of the image in memory is larger than the size you’re displaying it on screen. As such one of the most important things you can do to alleviate memory pressure in your app, is resizing your bitmaps.

Rather than writing all your own image resizing code, Android has a set of APIs which can do all this work for you. But the trick is, knowing which one to use?

For example, inSampleSize is the fastest way to down-scale your image; But you can only make it smaller by some factor of your image. createScaledBitmap is a great API, but requires an extra memory allocation to get it done.

Thankfully, Colt McAnlis covers all these topics (and more) in this video, helping you reduce your memory footprint, and get some smaller images.

Jul 5, 2015

Create custom text style

Example to create custom text style:


Modify /res/values/styles.xml to create our custom text style "LargeRedText", "InverseMediumBlueText", "GreenText", "ItalicGrayText" and "Bold50BlackText".
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    
    <style name="LargeRedText" parent="@android:style/TextAppearance.Large">
        <item name="android:textColor">#FF0000</item>
    </style>
    <style name="InverseMediumBlueText" parent="@android:style/TextAppearance.Medium.Inverse">
        <item name="android:background">#0000FF</item>
    </style>
    <style name="GreenText" parent="@android:style/TextAppearance">
        <item name="android:textColor">#00FF00</item>
    </style>
    <style name="ItalicGrayText" parent="@android:style/TextAppearance">
        <item name="android:textColor">#A0A0A0</item>
        <item name="android:textStyle">italic</item>
    </style>
    <style name="Bold50BlackText">
        <item name="android:textColor">#000000</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">50dp</item>
    </style>

</resources>


Example to use our custom text style in layout xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.androidtextappearance.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearance"
        android:textAppearance="?android:textAppearance" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceLarge"
        android:textAppearance="?android:textAppearanceLarge" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceMedium"
        android:textAppearance="?android:textAppearanceMedium" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceSmall"
        android:textAppearance="?android:textAppearanceSmall" />
    
 <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="custom style LargeRedText"
        style="@style/LargeRedText" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="custom style InverseMediumBlueText"
        style="@style/InverseMediumBlueText" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="custom style GreenText"
        style="@style/GreenText" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="custom style ItalicGrayText"
        style="@style/ItalicGrayText" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="custom style Bold50BlackText"
        style="@style/Bold50BlackText" />
    
</LinearLayout>


Example to set textAppearance in XML

Example to set textAppearance in XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.androidtextappearance.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearance"
        android:textAppearance="?android:textAppearance" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceLarge"
        android:textAppearance="?android:textAppearanceLarge" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceMedium"
        android:textAppearance="?android:textAppearanceMedium" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceSmall"
        android:textAppearance="?android:textAppearanceSmall" />
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceInverse"
        android:textAppearance="?android:textAppearanceInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceLargeInverse"
        android:textAppearance="?android:textAppearanceLargeInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceMediumInverse"
        android:textAppearance="?android:textAppearanceMediumInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="textAppearanceSmallInverse"
        android:textAppearance="?android:textAppearanceSmallInverse" />

 <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:text="textAppearanceInverse"
        android:textAppearance="?android:textAppearanceInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:text="textAppearanceLargeInverse"
        android:textAppearance="?android:textAppearanceLargeInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:text="textAppearanceMediumInverse"
        android:textAppearance="?android:textAppearanceMediumInverse" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:text="textAppearanceSmallInverse"
        android:textAppearance="?android:textAppearanceSmallInverse" />
    
</LinearLayout>



Jun 1, 2015

100 Days of Google Dev


Starting now, Google are releasing 100 developer videos over 100 days, covering from Chrome to Android. Subscribe now: http://goo.gl/mQyv5L


May 17, 2015

How Android OTA Updates work

Presentation at Embedded Linux Conference 2015 by Andrew Boie from Intel Corporation.

AOSP is distributed with the source code and tools for full (whole image) and incremental (binary patch) secure over-the-air (OTA) software updates, specifically an alternate boot target Recovery Console, the updater logic itself, and tools to create software updates. There is no publicly available documentation for how this mechanism is supposed to be integrated. This presentation gives a detailed end-to-end description of how software updates are created, digitally signed, and applied to the device. It includes a discussion on the plug-in architecture and Edify language which allows builders to customize the OTA updates with platform-specific features. This is an updated version of a talk presented at ABS in 2012, with details on new OTA features including block-level OTA updates in Lollipop.

Speakers
Andrew Boie
Intel Corporation
Andrew Boie is a software engineer and scrum master for the Intel Android-IA project hosted on 01.org, which aims to support Android on Intel Core and Atom platforms. Prior to working at Intel Andrew worked for Garmin International as an engineering team lead on Android Eclair-based Nuvifone projects. He spoke at ABS 2011 on the topic of Android OTA Software Updates.


May 12, 2015

Google Play Services 7.3

Google Play Services 7.3 brings a ton of great new features to help you BUILD BETTER APPS! This update brings the ability to connect multiple wearables simultaneously to a single phone.

There are also some great new updates to Google Fit, including nutrition types, and to Location.


May 6, 2015

Older YouTube apps is no longer be supported



If you see this video in your YouTube app’s video feeds, your device is affected. (Note: If the video appears unexpectedly in a web browser, it means that website is using an outdated method to access YouTube videos.)

As Google upgrade the YouTube Data API to bring more features, the old version will be begin shutting down on April 20, 2015. This will result in the current YouTube app not working on certain device models from 2012 and older.

https://youtube.com/devicesupport


May 4, 2015

Using VideoView to play mp4, with MediaController enable/disable

Example to play mp4 on SDCard/ExternalStorage using android.widget.VideoView. You can also enable/disable the MediaController, contains the buttons like "Play/Pause", "Rewind", "Fast Forward" and a progress slider, by calling VideoView.setMediaController().

With the MediaController set, tap on the video (or the VideoView) to display the controller.


Example code:
package com.example.androidvideoview;

import java.io.File;

import android.support.v7.app.ActionBarActivity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.VideoView;
import android.os.Bundle;
import android.os.Environment;

public class MainActivity extends ActionBarActivity {
 
 ToggleButton enableMediaController;
 VideoView myVideoView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  enableMediaController = (ToggleButton)findViewById(R.id.enableMediaController);
  myVideoView = (VideoView)findViewById(R.id.myvideoview);
  myVideoView.setVideoPath(getViewSrc());
  myVideoView.requestFocus();
  myVideoView.start();
  
  setMediaController();
  
  enableMediaController.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    setMediaController();
   }});
 }
 
 private void setMediaController(){
  if(enableMediaController.isChecked()){
   myVideoView.setMediaController(new MediaController(this));
  }else{
   myVideoView.setMediaController(null);
  }
 }

 private String getViewSrc(){
  File extStorageDirectory = Environment.getExternalStorageDirectory();
  String s = extStorageDirectory.getAbsolutePath() + "/test.mp4";
  Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
  return s;
 }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidvideoview.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />

    <ToggleButton
        android:id="@+id/enableMediaController"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOn="Disable MediaController"
        android:textOff="Enable MediaController"
        android:checked="true"/>
    <VideoView
        android:id="@+id/myvideoview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

To play the file in SD Card, <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> is needed in AndroidManifest.xml, otherwise "Can't play this video".


Apr 9, 2015

Android coding example to Set fontFamily

Android 4.1 adds several more variants of the Roboto font style for a total of 10 variants, and they're all usable by apps. Your apps now have access to the full set of both light and condensed variants. - http://developer.android.com/about/versions/android-4.1.html

Example:


MainActivity.java
package com.example.androidfront;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.graphics.Typeface;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
 
 String typeFaceName[] = {
  "sans-serif",
  "sans-serif-light",
  "sans-serif-condensed",
  "sans-serif-thin",
  "sans-serif-medium"};

 CheckBox checkBold, checkItalic;
 Spinner selTypeFace;
 EditText editArea;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  editArea = (EditText)findViewById(R.id.editarea);
  
  checkBold = (CheckBox)findViewById(R.id.boldsel);
  checkBold.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    updateFonts();
   }});
  
  checkItalic = (CheckBox)findViewById(R.id.italicsel);
  checkItalic.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    updateFonts();
   }});
  
  selTypeFace = (Spinner)findViewById(R.id.typefacesel);
  ArrayAdapter<String> adapter = 
   new ArrayAdapter<String>(this, 
    android.R.layout.simple_spinner_item, typeFaceName);
  adapter.setDropDownViewResource(
    android.R.layout.simple_spinner_dropdown_item);
  selTypeFace.setAdapter(adapter);
  selTypeFace.setOnItemSelectedListener(new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    updateFonts();
   }

   @Override
   public void onNothingSelected(AdapterView<?> parent) {}});

 }
 
 private void updateFonts(){

  int tfSel = selTypeFace.getSelectedItemPosition();
  String selTypeFaceName = typeFaceName[tfSel];
  
  int style;
  
  if(!checkBold.isChecked() && !checkItalic.isChecked()){
   style = Typeface.NORMAL;
  }else if(checkBold.isChecked() && !checkItalic.isChecked()){
   style = Typeface.BOLD;
  }else if(!checkBold.isChecked() && checkItalic.isChecked()){
   style = Typeface.ITALIC;
  }else{
   style = Typeface.BOLD_ITALIC;
  }
  
  Typeface tf = Typeface.create(selTypeFaceName, style);
  editArea.setTypeface(tf);

 }

}

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidfront.MainActivity"
    android:orientation="vertical" >
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
        
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >
            
            <TextView
                android:fontFamily="sans-serif"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:fontFamily="sans-serif-light"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:fontFamily="sans-serif-condensed"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:fontFamily="sans-serif-thin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:fontFamily="sans-serif-medium"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >
            
            <Spinner
                android:id="@+id/typefacesel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <CheckBox 
                android:id="@+id/boldsel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="BOLD"/>
            <CheckBox 
                android:id="@+id/italicsel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="ITALIC"/>
            <EditText
                android:id="@+id/editarea"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:singleLine="false"
                android:gravity="top"
                android:background="#E0E0E0"/>
        </LinearLayout>
        
        
    </LinearLayout>
</LinearLayout>

string resources of "test" is needed, read HERE.

Apr 7, 2015

Example to set fonts for Android

How to set fonts (Typeface and style) on Android using xml and programmatically.



package com.example.androidfront;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.graphics.Typeface;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
 
 String typeFaceName[] = {
  "DEFAULT",
  "DEFAULT_BOLD",
  "MONOSPACE",
  "SANS_SERIF",
  "SERIF"};
 
 Typeface typeFace[] = {
   Typeface.DEFAULT,
   Typeface.DEFAULT_BOLD,
   Typeface.MONOSPACE,
   Typeface.SANS_SERIF,
   Typeface.SERIF};

 CheckBox checkBold, checkItalic;
 Spinner selTypeFace;
 EditText editArea;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  editArea = (EditText)findViewById(R.id.editarea);
  
  checkBold = (CheckBox)findViewById(R.id.boldsel);
  checkBold.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    updateFonts();
   }});
  
  checkItalic = (CheckBox)findViewById(R.id.italicsel);
  checkItalic.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    updateFonts();
   }});
  
  selTypeFace = (Spinner)findViewById(R.id.typefacesel);
  ArrayAdapter<String> adapter = 
   new ArrayAdapter<String>(this, 
    android.R.layout.simple_spinner_item, typeFaceName);
  adapter.setDropDownViewResource(
    android.R.layout.simple_spinner_dropdown_item);
  selTypeFace.setAdapter(adapter);
  selTypeFace.setOnItemSelectedListener(new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    updateFonts();
   }

   @Override
   public void onNothingSelected(AdapterView<?> parent) {}});

 }
 
 private void updateFonts(){
  int tfSel = selTypeFace.getSelectedItemPosition();
  Typeface tf = typeFace[tfSel];
  editArea.setTypeface(tf);
  
  int style;
  
  if(!checkBold.isChecked() && !checkItalic.isChecked()){
   style = Typeface.NORMAL;
  }else if(checkBold.isChecked() && !checkItalic.isChecked()){
   style = Typeface.BOLD;
  }else if(!checkBold.isChecked() && checkItalic.isChecked()){
   style = Typeface.ITALIC;
  }else{
   style = Typeface.BOLD_ITALIC;
  }

  editArea.setTypeface(tf, style);
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidfront.MainActivity"
    android:orientation="vertical" >
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
        
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >
            
            <TextView
                android:typeface="normal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:typeface="monospace"
                android:textStyle="bold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:typeface="sans"
                android:textStyle="italic"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            <TextView
                android:typeface="serif"
                android:textStyle="bold|italic"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/test"/>
            
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >
            
            <Spinner
                android:id="@+id/typefacesel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <CheckBox 
                android:id="@+id/boldsel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="BOLD"/>
            <CheckBox 
                android:id="@+id/italicsel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="ITALIC"/>
            <EditText
                android:id="@+id/editarea"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:singleLine="false"
                android:gravity="top"
                android:background="#E0E0E0"/>
        </LinearLayout>
        
        
    </LinearLayout>
</LinearLayout>

Add <string name="test"> in /res/values/strings.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidFront</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="test">ABCDEfghijKLMNOpqrstUVWXYz1234567890</string>
</resources>


Mar 17, 2015

Get number of available cores and cpu info

The method Runtime.availableProcessors() returns the number of processor cores available to the VM.

And the /proc/cpuinfo hold infoprmation about the CPU, you can read it as text file.



Example:
package com.example.androidcpuinfo;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 TextView cores, cpuinfo;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cores = (TextView)findViewById(R.id.cores);
        cpuinfo = (TextView)findViewById(R.id.cpuinfo);
        
        Runtime runtime = Runtime.getRuntime();
        int availableProcessors = runtime.availableProcessors();
        cores.setText("You have " + availableProcessors + " availableProcessors");
        
        //Read text file "/proc/cpuinfo"
        String file_cpuinfo = "/proc/cpuinfo";
        String info = "";
        try {
   FileReader fileReader = new FileReader(file_cpuinfo);
   BufferedReader bufferReader = new BufferedReader(fileReader);

   String line;
         try {
    while((line = bufferReader.readLine()) != null)
    {
     info += line + "\n";
    }
    cpuinfo.setText(info);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
         
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidcpuinfo.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="24dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/cores"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textStyle="italic" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/cpuinfo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>

Mar 7, 2015

Create mirror bitmap using Matrix



package com.example.androidmirrorimage;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

 ImageView image1, image2;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);

  Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  
  image1.setImageBitmap(bm);
  image2.setImageBitmap(getMirrorBitmap(bm));

 }

 private Bitmap getMirrorBitmap(Bitmap src) {

  Matrix matrix = new Matrix();
  matrix.preScale(1, -1);
  Bitmap result = Bitmap.createBitmap(
    src, 0, 0, src.getWidth(), src.getHeight(), matrix, false);
  return result;
 }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidmirrorimage.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

Feb 24, 2015

Introduction to Android Studio

A high level introduction to Android Studio, the new IDE for Android application development. Learn why you should migrate your projects to Android Studio now and how it can help you be more productive as a developer. Rich layout editor, handy suggestions and fixes, new Android project view - these are just some of the things you can expect from the IDE, which is built on the successful IntelliJ IDEA.

Feb 23, 2015

Custom ImageView to show touched portion only

Here is a custom ImageView (TouchImageView), override onTouchEvent(MotionEvent event) and onDraw(Canvas canvas) methods, to make it display the touched portion only.


package com.example.androidtouchimageview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

public class TouchImageView extends ImageView {

 private float radius = 0;
 private Paint paint = null;

 private float x;
 private float y;
 private boolean touched = false;

 public TouchImageView(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
 }

 public TouchImageView(Context context, AttributeSet attrs) {
  super(context, attrs);
  // TODO Auto-generated constructor stub
 }

 public TouchImageView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  // TODO Auto-generated constructor stub
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  int action = event.getAction();
  touched = (action == MotionEvent.ACTION_DOWN 
    || action == MotionEvent.ACTION_MOVE);
  x = event.getX();
  y = event.getY();
  
  int w = getWidth();
  int h = getHeight();
  if(w>=h){
   radius = h * event.getSize();
  }else{
   radius = w * event.getSize();
  }
  
  invalidate();
  return true;
 }

 @Override
 protected void onDraw(Canvas canvas) {
  if (paint == null) {
   Bitmap bm = Bitmap.createBitmap(
    getWidth(), 
    getHeight(),
    Bitmap.Config.ARGB_8888);
   Canvas originalCanvas = new Canvas(bm);
   super.onDraw(originalCanvas);

   Shader shader = new BitmapShader(bm, 
    Shader.TileMode.CLAMP,
    Shader.TileMode.CLAMP);

   paint = new Paint();
   paint.setShader(shader);
  }

  canvas.drawColor(getSolidColor());
  if (touched) {
   canvas.drawCircle(x, y, radius, paint);
  }
 }

}


Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidtouchimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />
    
    <com.example.androidtouchimageview.TouchImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    
    <com.example.androidtouchimageview.TouchImageView
        android:id="@+id/image2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Feb 22, 2015

Implement color animation with ValueAnimator

To implement color animation with ValueAnimator:


package com.example.valueanimatorofcolor;

import com.example.objectanimatorofargb.R;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView title;
 Button btnStart;
 ImageView image;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  title = (TextView) findViewById(R.id.title);
  image = (ImageView) findViewById(R.id.image);
  btnStart = (Button) findViewById(R.id.start);
  
  btnStart.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    startColorAnimation(image);
   }});
 }
 
 private void startColorAnimation(View view){
  //int colorStart = 0xFFffffff;
  int colorStart = view.getSolidColor();
  int colorEnd   = 0xFF000000;

  ValueAnimator colorAnim = ObjectAnimator.ofInt(
    view, "backgroundColor", colorStart, colorEnd);
  colorAnim.setDuration(2000);
  colorAnim.setEvaluator(new ArgbEvaluator());
  colorAnim.setRepeatCount(1);
  colorAnim.setRepeatMode(ValueAnimator.REVERSE);
  colorAnim.start();
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.valueanimatorofcolor.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Animation" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Feb 20, 2015

Example of Reveal animations on Android 5.0

Android 5.0, added in API level 21, introduce ViewAnimationUtils.createCircularReveal (View view, int centerX, int centerY, float startRadius, float endRadius) method returns an Animator which can animate a clipping circle, to animate a clipping circle to reveal or hide a view.


package com.example.androidrevealeffect;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

 TextView title;
 ImageView image;
 ToggleButton btnHideShow;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  title = (TextView)findViewById(R.id.title);
  image = (ImageView) findViewById(R.id.image);
  btnHideShow = (ToggleButton) findViewById(R.id.hideshow);

  btnHideShow.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    if(isChecked){
     hide(title);
     hide(image);
    }else{
     show(title);
     show(image);
    }

   }
  });
 }

 // To reveal a previously invisible view using this effect:
 private void show(final View view) {
  // get the center for the clipping circle
  int cx = (view.getLeft() + view.getRight()) / 2;
  int cy = (view.getTop() + view.getBottom()) / 2;

  // get the final radius for the clipping circle
  int finalRadius = Math.max(view.getWidth(), view.getHeight());

  // create the animator for this view (the start radius is zero)
  Animator anim = ViewAnimationUtils.createCircularReveal(view, cx, cy,
    0, finalRadius);
  anim.setDuration(1000);

  // make the view visible and start the animation
  view.setVisibility(View.VISIBLE);
  anim.start();
 }

 // To hide a previously visible view using this effect:
 private void hide(final View view) {

  // get the center for the clipping circle
  int cx = (view.getLeft() + view.getRight()) / 2;
  int cy = (view.getTop() + view.getBottom()) / 2;

  // get the initial radius for the clipping circle
  int initialRadius = view.getWidth();

  // create the animation (the final radius is zero)
  Animator anim = ViewAnimationUtils.createCircularReveal(view, cx, cy,
    initialRadius, 0);
  anim.setDuration(1000);

  // make the view invisible when the animation is done
  anim.addListener(new AnimatorListenerAdapter() {
   @Override
   public void onAnimationEnd(Animator animation) {
    super.onAnimationEnd(animation);
    view.setVisibility(View.INVISIBLE);
   }
  });

  // start the animation
  anim.start();
 }

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidrevealeffect.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <ToggleButton
        android:id="@+id/hideshow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOn="Show"
        android:textOff="Hide" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher"
        android:background="@android:color/darker_gray" />

</LinearLayout>

Feb 19, 2015

ObjectAnimator to animate coordinates along a path

In Android 5.0, android:minSdkVersion="21", ObjectAnimator has a new constructors that enable you to animate coordinates along a path using two or more properties at once. Here is a example:


package com.example.androidobjectanimator;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Path;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

 LinearLayout mainLayout;
 TextView textTitle;
 Button buttonMove;
 ImageView image;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mainLayout = (LinearLayout) findViewById(R.id.mainlayout);
  mainLayout.setOnClickListener(MyOnClickListener);
  textTitle = (TextView) findViewById(R.id.title);
  textTitle.setOnClickListener(MyOnClickListener);
  buttonMove = (Button) findViewById(R.id.buttonflip);
  buttonMove.setOnClickListener(MyOnClickListener);
  image = (ImageView) findViewById(R.id.image);
  image.setOnClickListener(MyOnClickListener);
 }

 OnClickListener MyOnClickListener = 
  new OnClickListener() {

  @Override
  public void onClick(View v) {
   moveit(v);
  }

 };

 private void moveit(final View view) {

  float x = view.getX();
  float y = view.getY();
  Path path = new Path();

  path.moveTo(x + 0, y + 0);
  path.lineTo(x + 100, y + 150);
  path.lineTo(x + 400, y + 150);
  path.lineTo(x + 0, y + 0);
  ObjectAnimator objectAnimator = 
   ObjectAnimator.ofFloat(view, View.X,
    View.Y, path);
  objectAnimator.setDuration(3000);
  objectAnimator.start();
 }

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidflipview.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />
    
    <Button
        android:id="@+id/buttonflip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Move" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    
</LinearLayout>

Feb 7, 2015

ObjectAnimator example to rotate view


package com.example.androidflipview;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.animation.ObjectAnimator;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 LinearLayout mainLayout;
 TextView textTitle;
 Button buttonFlip;
 ImageView image;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
  mainLayout.setOnClickListener(MyOnClickListener);
  textTitle = (TextView)findViewById(R.id.title);
  textTitle.setOnClickListener(MyOnClickListener);
  buttonFlip = (Button)findViewById(R.id.buttonflip);
  buttonFlip.setOnClickListener(MyOnClickListener);
  image = (ImageView)findViewById(R.id.image);
  image.setOnClickListener(MyOnClickListener);

 }
 
 OnClickListener MyOnClickListener = new OnClickListener(){

  @Override
  public void onClick(View v) {
   rotateit(v);
  }
  
 };

    private void rotateit(final View viewToFlip) {
     ObjectAnimator rot = ObjectAnimator.ofFloat(viewToFlip, "rotation", 0f, 360f);
     rot.setDuration(3000);
        rot.start();
     
    }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidflipview.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />
    
    <Button
        android:id="@+id/buttonflip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Rotate" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    
</LinearLayout>

Feb 5, 2015

Flip view vertically


package com.example.androidflipview;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.animation.ObjectAnimator;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 LinearLayout mainLayout;
 TextView textTitle;
 Button buttonFlip;
 ImageView image;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
  mainLayout.setOnClickListener(MyOnClickListener);
  textTitle = (TextView)findViewById(R.id.title);
  textTitle.setOnClickListener(MyOnClickListener);
  buttonFlip = (Button)findViewById(R.id.buttonflip);
  buttonFlip.setOnClickListener(MyOnClickListener);
  image = (ImageView)findViewById(R.id.image);
  image.setOnClickListener(MyOnClickListener);

 }
 
 OnClickListener MyOnClickListener = new OnClickListener(){

  @Override
  public void onClick(View v) {
   flipit(v);
  }
  
 };

    private void flipit(final View viewToFlip) {
     ObjectAnimator flip = ObjectAnimator.ofFloat(viewToFlip, "rotationX", 0f, 360f);
     flip.setDuration(3000);
        flip.start();
     
    }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidflipview.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />
    
    <Button
        android:id="@+id/buttonflip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flip" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    
</LinearLayout>

Feb 3, 2015

Implement flipping animation horizontally with ObjectAnimator


package com.example.androidflipview;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.animation.ObjectAnimator;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 TextView textTitle;
 Button buttonFlip;
 ImageView image;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textTitle = (TextView)findViewById(R.id.title);
  textTitle.setOnClickListener(MyOnClickListener);
  buttonFlip = (Button)findViewById(R.id.buttonflip);
  buttonFlip.setOnClickListener(MyOnClickListener);
  image = (ImageView)findViewById(R.id.image);
  image.setOnClickListener(MyOnClickListener);

 }
 
 OnClickListener MyOnClickListener = new OnClickListener(){

  @Override
  public void onClick(View v) {
   flipit(v);
  }
  
 };

    private void flipit(final View viewToFlip) {
     ObjectAnimator flip = ObjectAnimator.ofFloat(viewToFlip, "rotationY", 0f, 360f);
     flip.setDuration(3000);
        flip.start();
     
    }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidflipview.MainActivity" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />
    
    <Button
        android:id="@+id/buttonflip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flip" />
    
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />
    
</LinearLayout>

Jan 27, 2015

Android EffectFactory example

It's a good example of using android.media.effect.EffectFactory. It can be found in your Android SDK folder, normally at:
.../Android/sdk/samples/android-21/legacy/HelloEffects

The EffectFactory class defines the list of available Effects, and provides functionality to inspect and instantiate them.


Jan 21, 2015

Display emoji from byte[], encoded using UTF-8

Example show how to display emoji on TextView, encoded from byte[].


To convert byte array to String using charset of UTF-8, we can call the constructor of String:
new String(bytes, "UTF-8")

Example:
package com.example.androidemoji;

import java.io.UnsupportedEncodingException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  TextView emojiText = (TextView)findViewById(R.id.emojitext);
  
  //byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x81};
  //byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x84};
  byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x89};
  try {
   emojiText.setText(new String(bytes, "UTF-8"));
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  //Direct type in the emoji
  //emojiText.setText("😁");  //maybe cannot displayed on browser

 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidemoji.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/emojitext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="100dp"
        android:textStyle="bold" />

</LinearLayout>

The page Emoji Unicode Tables show commonly-supported Emoji that map to standardized Unicode characters.

Jan 13, 2015

Android ListView, scroll to specified position

How to scroll Android ListView to top, bottom or specified position.

package com.example.androidlistviewscrolling;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 String[] months = { "January", "February", "March", "April", "May", "June",
   "July", "August", "September", "October", "November", "December" };

 ListView listView;
 int toPosition = months.length;
 
 Button btnScrollTop, btnScrollBottom, btnScrollTo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listview);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, months);
  listView.setAdapter(adapter);
  
  listView.setOnItemClickListener(new OnItemClickListener(){

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    toPosition = position;
    btnScrollTo.setText("Scroll to position " + toPosition);
   }});
  
  btnScrollTop = (Button)findViewById(R.id.scrolltop);
  btnScrollTop.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    listView.smoothScrollToPosition(0);
   }});
  
  btnScrollBottom = (Button)findViewById(R.id.scrollbottom);
  btnScrollBottom.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    listView.smoothScrollToPosition(listView.getCount()-1);
   }});
  
  btnScrollTo = (Button)findViewById(R.id.scrollto);
  btnScrollTo.setText("Scroll to position " + toPosition);
  btnScrollTo.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    listView.smoothScrollToPosition(toPosition);
   }});
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidlistviewscrolling.MainActivity" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="28dp"
            android:text="android-coding.blogspot.com" />
        
        <Button
            android:id="@+id/scrolltop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Scroll to Top" />
        <Button
            android:id="@+id/scrollbottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Scroll to Bottom" />
        <Button
            android:id="@+id/scrollto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

Jan 10, 2015

List running service of Android device

The method getRunningServices(int maxNum) of ActivityManager return a list of the services that are currently running. (Note: this method is only intended for debugging or implementing service management type user interfaces)


package com.example.androidgetrunning;

import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.app.ActivityManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  
  ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);

  /*
   * maxNum: the maximum number of entries to return in the list. 
   * The actual number returned may be smaller, 
   * depending on how many services are running.
   */
  int maxNum = 100;
  List<ActivityManager.RunningServiceInfo> list = activityManager.getRunningServices(maxNum);
  
  StringBuilder info = new StringBuilder();
  info.append("android-coding.blogspot.com" + "\n\n");
  info.append("no. of running service: " + list.size() + "\n\n");
  for(int i=0; i<list.size(); i++){
   info.append(list.get(i).service + "\n\n");
  }
  
  TextView texView = new TextView(this);
  texView.setMovementMethod(new ScrollingMovementMethod());
  texView.setText(info);
  setContentView(texView);
 }

}

List running application processes of Android device

Call getSystemService(ACTIVITY_SERVICE) to get instance of the ActivityManager. With it, your app can interact with the overall activities running in the system. The method getRunningAppProcesses() return a list of application processes that are running on the device. (Note: this method is only intended for debugging or building a user-facing process management UI)

Example:
package com.example.androidgetrunning;

import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.app.ActivityManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
  
  List<ActivityManager.RunningAppProcessInfo> list = activityManager.getRunningAppProcesses();
  
  StringBuilder info = new StringBuilder();
  info.append("android-coding.blogspot.com" + list.size() + "\n\n");
  info.append("no. of running application processes: " + list.size() + "\n");
  for(int i=0; i<list.size(); i++){
   info.append(list.get(i).processName + "\n");
  }
  
  TextView texView = new TextView(this);
  texView.setMovementMethod(new ScrollingMovementMethod());
  texView.setText(info);
  setContentView(texView);
 }

}


Android Vector Graphics

Tenghui Zhu presents the VectorDrawable and AnimatedVectorDrawable APIs in Android L, which can provide an easy and compact way to represent the drawables. These APIs also helps adding various animations to the drawables, including path morphing.

To learn more about vector drawable support in Android, check out http://goo.gl/fj7gv2


Infolinks In Text Ads