Apr 29, 2013

Display HTML String with img on TextView, with Html.ImageGetter

Example to display HTML String with img on TextView. To display image in TextView, we have to implement interface of Html.ImageGetter.

package com.example.androidhtmltextview;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 String htmlString = "<img src='ic_launcher'><i>Welcome to<i> <b><a href='http://android-coding.blogspot.com'>Android Coding</a></b>";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  TextView htmlTextView = new TextView(this);
  setContentView(htmlTextView);
  
  htmlTextView.setText(Html.fromHtml(htmlString, new Html.ImageGetter(){

   @Override
   public Drawable getDrawable(String source) {
    Drawable drawable;
    int dourceId = 
      getApplicationContext()
      .getResources()
      .getIdentifier(source, "drawable", getPackageName());
    
    drawable = 
      getApplicationContext()
      .getResources()
      .getDrawable(dourceId);
    
    drawable.setBounds(
      0, 
      0, 
      drawable.getIntrinsicWidth(),
      drawable.getIntrinsicHeight());
    
    return drawable;
   }
   
  }, null));
  
  htmlTextView.setMovementMethod(LinkMovementMethod.getInstance());
  
 }

}


Display HTML String with img on TextView
Display HTML String with img on TextView


Next: Display HTML String with multi images on TextView, with Html.ImageGetter

Display HTML String with link on TextView

Example to display HTML String with link on TextView:

package com.example.androidhtmltextview;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 String htmlString = "<i>Welcome to<i> <b><a href='http://android-coding.blogspot.com'>Android Coding</a></b>";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  TextView htmlTextView = new TextView(this);
  setContentView(htmlTextView);
  
  htmlTextView.setText(Html.fromHtml(htmlString));
  htmlTextView.setMovementMethod(LinkMovementMethod.getInstance());
  
 }

}


Display HTML String with link on TextView
Display HTML String with link on TextView


Display HTML strings on TextView using android.text.Html.fromHtml()

Example to Display HTML strings on TextView using android.text.Html.fromHtml():

package com.example.androidhtmltextview;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 String htmlString = "<i>Welcome to<i> <b>Android Coding</b>";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  TextView htmlTextView = new TextView(this);
  setContentView(htmlTextView);
  
  htmlTextView.setText(Html.fromHtml(htmlString));
  
 }

}



Display HTML strings on TextView using android.text.Html.fromHtml()
Display HTML strings on TextView using android.text.Html.fromHtml()


Apr 27, 2013

handle DialogFragment with orientaion change

To handle DialogFragment with orientaion change:
  • Override onActivityCreated() to call setRetainInstance(true)

    Example:

      @Override
      public void onActivityCreated(Bundle savedInstanceState) {
       // TODO Auto-generated method stub
       super.onActivityCreated(savedInstanceState);
       setRetainInstance(true);
      }
    

  • Override onDestroyView() to dismiss message quere

    Example:

      @Override
      public void onDestroyView() {
       if (getDialog() != null && getRetainInstance()){
        getDialog().setDismissMessage(null);
       }
       super.onDestroyView();
      }
    


Apr 25, 2013

Show and Hide ActionBar using Java code

Toggle ActionBar


Example Code:

package com.example.androidtoggleactionbar;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Button buttonToggleActionBar = new Button(this);
  buttonToggleActionBar.setText("Toggle ActionBar");
  setContentView(buttonToggleActionBar);
  
  buttonToggleActionBar.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    if(getActionBar().isShowing()){
     getActionBar().hide();
    }else{
     getActionBar().show();
    }
   }});
 }
}


Apr 18, 2013

Implement custom title

App with custom title
App with custom title


Create /res/layout/custom_title.xml, to define the layout of your custom title bar.
<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" >

 <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>
    <TextView
        android:id="@+id/titletext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textStyle="italic|bold"
        android:text="http://android-coding.blogspot.com/" />
    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>

</LinearLayout>


MainActivity.java
package com.example.androidcustomtitle;

import android.os.Bundle;
import android.app.Activity;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

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

  boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
  
  setContentView(R.layout.activity_main);
  
  if(customTitleSupported){
   getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
   Toast.makeText(getApplicationContext(), 
     "Custom Title Applied", 
     Toast.LENGTH_LONG).show();
   
   //Set title text programmatically
   TextView titleText = (TextView)findViewById(R.id.titletext);
   titleText.setText("Android-Coding");
   
  }else{
   Toast.makeText(getApplicationContext(), 
     "FEATURE_CUSTOM_TITLE not supported!", 
     Toast.LENGTH_LONG).show();
  }

 }

}


Also modify AndroidManifest.xml to use style without title features on android:theme; otherwise "android.util.AndroidRuntimeException: You cannot combine custom titles with other title features" will be thrown. "@android:style/Theme.Light" and "@android:style/Theme.Black" have been tested work ok.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidcustomtitle"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Light" >
        <activity
            android:name="com.example.androidcustomtitle.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Apr 10, 2013

Create intent to specified video or playlist in Youtube App

Before start coding using YouTube Android Player API, read the post to prepare your development tools.

com.google.android.youtube.player.YouTubeIntents of the YouTube Android Player API provides static methods that create intents which navigate to specific activities within the main YouTube application.


Example:

Create intent to specified video in Youtube App


package com.example.androidplayvideointent;

import com.google.android.youtube.player.YouTubeIntents;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 
 private static final String VIDEO_ID = "fhWaJi1Hsfo";
 
 Button startYoutube;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  startYoutube = (Button)findViewById(R.id.startyoutube);
  startYoutube.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    Intent intentStartYoutube = 
      YouTubeIntents.createPlayVideoIntent(getApplicationContext(), VIDEO_ID);
    startActivity(intentStartYoutube);
   }});
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}


<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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/startyoutube"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Youtube App" />

</LinearLayout>


Apr 6, 2013

Display YouTubeThumbnailView of YouTube Android Player API

Before start coding using YouTube Android Player API, read the post to prepare your development tools.

Example:

YouTubeThumbnailView
YouTubeThumbnailView


package com.example.androidyoutubethumbnailview;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Toast;

public class MainActivity extends Activity 
 implements YouTubeThumbnailView.OnInitializedListener{
 
 public static final String DEVELOPER_KEY = "replace your own API Key here";
 private static final String VIDEO_ID = "fhWaJi1Hsfo";

 private YouTubeThumbnailLoader youTubeThumbnailLoader;
 private YouTubeThumbnailView thumbnailView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  thumbnailView = (YouTubeThumbnailView)findViewById(R.id.thumbnailview);
  thumbnailView.initialize(DEVELOPER_KEY, this);
 }

 @Override
 public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
   YouTubeInitializationResult errorReason) {
  
  String errorMessage =
    String.format("onInitializationFailure (%1$s)", 
      errorReason.toString());
  Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); 
 }

 @Override
 public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
   YouTubeThumbnailLoader thumbnailLoader) {
  
  Toast.makeText(getApplicationContext(), 
         "onInitializationSuccess", Toast.LENGTH_SHORT).show();
  
  youTubeThumbnailLoader = thumbnailLoader;
     thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailListener());
     
     youTubeThumbnailLoader.setVideo(VIDEO_ID);
 }
 
   private final class ThumbnailListener implements
       YouTubeThumbnailLoader.OnThumbnailLoadedListener {

     @Override
     public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
       Toast.makeText(getApplicationContext(), 
         "onThumbnailLoaded", Toast.LENGTH_SHORT).show();
     }

     @Override
     public void onThumbnailError(YouTubeThumbnailView thumbnail,
         YouTubeThumbnailLoader.ErrorReason reason) {
      Toast.makeText(getApplicationContext(), 
        "onThumbnailError", Toast.LENGTH_SHORT).show();
     }  
   }

}


<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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <com.google.android.youtube.player.YouTubeThumbnailView
        android:id="@+id/thumbnailview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


Apr 5, 2013

Example to use YouTubePlayerFragment of YouTube Android Player API

Before start coding using YouTube Android Player API, read the post to prepare your development tools.

Example to use YouTubePlayerFragment
Example to use YouTubePlayerFragment


To use YouTubePlayerFragment in your app, android:minSdkVersion have to be set "11" or higher.

Modify activity_main.xml to include <fragment> of "com.google.android.youtube.player.YouTubePlayerFragment" in your 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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <fragment
      android:name="com.google.android.youtube.player.YouTubePlayerFragment"
      android:id="@+id/youtubeplayerfragment"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</LinearLayout>


Modify MainActivity.java, to extend YouTubeBaseActivity and implements YouTubePlayer.OnInitializedListener. Replace your the String DEVELOPER_KEY with your own API Key obtain in the post "Preparation for development with YouTube Android Player API".
package com.example.androidyoutubeplayerfragment;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;

import android.os.Bundle;
import android.widget.Toast;
import android.content.Intent;

public class MainActivity extends YouTubeBaseActivity 
 implements YouTubePlayer.OnInitializedListener{
 
 public static final String DEVELOPER_KEY = "replace your own API Key here";
 private static final int RECOVERY_DIALOG_REQUEST = 1;
 private static final String VIDEO_ID = "fhWaJi1Hsfo";
 
 YouTubePlayerFragment myYouTubePlayerFragment;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
    .findFragmentById(R.id.youtubeplayerfragment);
  myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
 }
 
 @Override
 public void onInitializationFailure(YouTubePlayer.Provider provider,
   YouTubeInitializationResult errorReason) {
  if (errorReason.isUserRecoverableError()) {
   errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show(); 
  } else {
   String errorMessage = String.format(
     "There was an error initializing the YouTubePlayer (%1$s)", 
     errorReason.toString());
   Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); 
  } 
 }

 @Override
 public void onInitializationSuccess(Provider provider, YouTubePlayer player,
   boolean wasRestored) {
  if (!wasRestored) {
        player.cueVideo(VIDEO_ID);      
  }
 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  
  if (requestCode == RECOVERY_DIALOG_REQUEST) {
   // Retry initialization if user performed a recovery action
   getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this); 
  } 
 }

 protected YouTubePlayer.Provider getYouTubePlayerProvider() {
  return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment); 
 }

}


Apr 4, 2013

Implement Youtube Player using experimental YouTube Android Player API

Before start coding using YouTube Android Player API, read the post to prepare your development tools.

Youtube Player using experimental YouTube Android Player API
Youtube Player using experimental YouTube Android Player API


Modify activity_main.xml to include <com.google.android.youtube.player.YouTubePlayerView> in your 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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


Modify MainActivity.java, to extend YouTubeBaseActivity and implements YouTubePlayer.OnInitializedListener. Replace your the String DEVELOPER_KEY with your own API Key obtain in last post.

package com.example.androidyoutube;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

import android.os.Bundle;
import android.widget.Toast;
import android.content.Intent;

public class MainActivity extends YouTubeBaseActivity 
 implements YouTubePlayer.OnInitializedListener{
 
 public static final String DEVELOPER_KEY = "replace your own API Key here";
 private static final int RECOVERY_DIALOG_REQUEST = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
     youTubeView.initialize(DEVELOPER_KEY, this);
 }

   @Override
   public void onInitializationFailure(YouTubePlayer.Provider provider,
       YouTubeInitializationResult errorReason) {
     if (errorReason.isUserRecoverableError()) {
       errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
     } else {
       String errorMessage = String.format(
         "There was an error initializing the YouTubePlayer (%1$s)", 
         errorReason.toString());
       Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
     }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == RECOVERY_DIALOG_REQUEST) {
       // Retry initialization if user performed a recovery action
       getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
     }
   }

   protected YouTubePlayer.Provider getYouTubePlayerProvider() {
      return (YouTubePlayerView) findViewById(R.id.youtube_view);    
   }

   @Override
   public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
       boolean wasRestored) {
    
    if (!wasRestored) {
     player.cueVideo("fhWaJi1Hsfo");  
    }  
   }

}


Preparation for development with YouTube Android Player API

  • The YouTube Android Player API is an experimental API version, which means it is still in development, though we do not expect major interface changes. Until the experimental label is removed, the Deprecation Policy for YouTube APIs won't apply to this version as discussed in the API Terms of Service.

  • Download and install YouTube Android Player API

    - After download and unzip, copy the file YouTubeAndroidPlayerApi.jar from the libs folder in your unzipped files to /libs/ folder under your project.

    - Add the jar in your build path: Right click your project -> Properties -> Select Java Build Path on left -> select Libraries tab -> click Add JARS... button - Browse to select the added YouTubeAndroidPlayerApi.jar.

  • Register your application and obtain API from Google APIs Console.

    Check HERE your detail instructions.

  • Add <uses-permission> of "android.permission.INTERNET" in project AndroidManifest.xml.

  • If you use YouTubePlayerFragment, android:minSdkVersion have to be set "11" or higher.


Examples:


YouTube Android Player API Overview


Related:

Infolinks In Text Ads