Feb 25, 2014

ExpandableListView with icon

This example display icon in ExpandableListView.
ExpandableListView with icon
ExpandableListView with icon
Modify /res/layout/group_layout.xml to add a TextView to display our icon.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:orientation="horizontal"
    android:padding="8dp" >

    <ImageView
        android:id="@+id/groupimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
        
        
    <TextView
        android:id="@+id/group"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

</LinearLayout>

Modify getGroupView() in MyBaseExpandableListAdapter.java to set ImageView.
package com.example.androidexpandablelistview;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter {
 
 private Context context;
    private List<String> listGroup;
    private HashMap<String, List<String>> listChild;

 public MyBaseExpandableListAdapter(Context c, List<String> lg,
            HashMap<String, List<String>> lc) {
  context = c;
  listGroup = lg;
  listChild = lc;
 }

 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return listChild.get(listGroup.get(groupPosition)).get(childPosition);
 }

 @Override
 public long getChildId(int groupPosition, int childPosition) {
  return childPosition;
 }

 @Override
 public View getChildView(int groupPosition, int childPosition, 
   boolean isLastChild, View convertView, ViewGroup parent) {
  
        if (convertView == null) {
            LayoutInflater infalInflater = 
              (LayoutInflater)context
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.item_layout, null);
        }
 
        TextView textViewItem = 
          (TextView)convertView.findViewById(R.id.item);
        
        String text = (String)getChild(groupPosition, childPosition);
 
        textViewItem.setText(text);
        return convertView;
 }

 @Override
 public int getChildrenCount(int groupPosition) {
  return listChild.get(listGroup.get(groupPosition)).size();
 }

 @Override
 public Object getGroup(int groupPosition) {
  return listGroup.get(groupPosition);
 }

 @Override
 public int getGroupCount() {
  return listGroup.size();
 }

 @Override
 public long getGroupId(int groupPosition) {
  return groupPosition;
 }

 @Override
 public View getGroupView(int groupPosition, 
   boolean isExpanded, View convertView, 
   ViewGroup parent) {
  
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater)context
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.group_layout, null);
        }
        
        String textGroup = (String)getGroup(groupPosition);

        //get application resource/drawable not in Activity class, using context
        Resources contextResources = context.getResources();
        Drawable groupDrawable = contextResources.getDrawable(R.drawable.ic_launcher);
        //Set ImageView
        ImageView groupImage = (ImageView)convertView.findViewById(R.id.groupimage);
        groupImage.setImageDrawable(groupDrawable);
 
        TextView textViewGroup = (TextView)convertView.findViewById(R.id.group);
        textViewGroup.setText(textGroup);
 
        return convertView;
 }

 @Override
 public boolean hasStableIds() {
  return false;
 }

 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return true;
 }

}


Remark: Alternatively, you can set android:src in XML directly.

- For MainActivity.java and activity_main.xml, refer to last post "Detect user action on ExpandableListView, with various Listeners".
- For item_layout.xml, refer to the post "ExpandableListView example".

Feb 24, 2014

Detect user action on ExpandableListView, with various Listeners

This example implement various Listeners (OnChildClickListener, OnGroupClickListener, OnGroupCollapseListener and OnGroupExpandListener) to monitor user click on ExpandableListView.

ExpandableListView with Listeners
ExpandableListView with Listeners
MainActivity.java
package com.example.androidexpandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 MyBaseExpandableListAdapter myBaseExpandableListAdapter;
    ExpandableListView myExpandableListView;
    List<String> myListForGroup;
    HashMap<String, List<String>> myMapForChild;
 
    TextView info;
    
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  info = (TextView)findViewById(R.id.info);
  
  myExpandableListView = (ExpandableListView)
    findViewById(R.id.myexpandablelistview);
 
        initData();
 
        myBaseExpandableListAdapter = new 
          MyBaseExpandableListAdapter(this, myListForGroup, myMapForChild);
 
        myExpandableListView.setAdapter(myBaseExpandableListAdapter);
        
        myExpandableListView.setOnChildClickListener(myOnChildClickListener);
        myExpandableListView.setOnGroupClickListener(myOnGroupClickListener);
        myExpandableListView.setOnGroupCollapseListener(myOnGroupCollapseListener);
        myExpandableListView.setOnGroupExpandListener(myOnGroupExpandListener);
 }
 
 private void initData() {
  myListForGroup = new ArrayList<String>();
  myMapForChild = new HashMap<String, List<String>>();

        List<String> listGroupA = new ArrayList<String>();
        listGroupA.add("A - 1");
        listGroupA.add("A - 2");
        listGroupA.add("A - 3");

        List<String> listGroupB = new ArrayList<String>();
        listGroupB.add("B - 1");
 
        List<String> listGroupC = new ArrayList<String>();
        listGroupC.add("C - 1");
        listGroupC.add("C - 2");
        
        myListForGroup.add("Group A");
        myListForGroup.add("Group B");
        myListForGroup.add("Group C");
        
        myMapForChild.put(myListForGroup.get(0), listGroupA);
        myMapForChild.put(myListForGroup.get(1), listGroupB);
        myMapForChild.put(myListForGroup.get(2), listGroupC);
    }
 
 OnChildClickListener myOnChildClickListener =
  new OnChildClickListener(){

   @Override
   public boolean onChildClick(ExpandableListView parent, 
    View v, int groupPosition, int childPosition, long id) {
    String strChild = (String)myBaseExpandableListAdapter
      .getChild(groupPosition, childPosition);
    info.setText("child clicked: " + strChild);
    return true;
   }};
   
 OnGroupClickListener myOnGroupClickListener =
  new OnGroupClickListener(){

   @Override
   public boolean onGroupClick(ExpandableListView parent, 
     View v, int groupPosition, long id) {
    String strGroup = (String)myBaseExpandableListAdapter
      .getGroup(groupPosition);
    info.setText("group clicked: " + strGroup);
    
    return false;
    //return false
    //otherwise, group will not expand when user click on it
   }};
  
 OnGroupCollapseListener myOnGroupCollapseListener =
  new OnGroupCollapseListener(){

   @Override
   public void onGroupCollapse(int groupPosition) {
    info.setText("group collapse: " + groupPosition);
   }};
   
 OnGroupExpandListener myOnGroupExpandListener =
  new OnGroupExpandListener(){

   @Override
   public void onGroupExpand(int groupPosition) {
    info.setText("group expand: " + groupPosition);
   }};

}

/res/layout/activity_main.xml, modify to add a TextView to display info.
<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=".MainActivity" >

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

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <ExpandableListView
        android:id="@+id/myexpandablelistview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

For other files, MyBaseExpandableListAdapter.java, group_layout.xml and item_layout.xml, refer to ExpandableListView example.

Next:
- ExpandableListView with icon

Feb 23, 2014

ExpandableListView example

android.widget.ExpandableListView display two-level ListView: groups which can individually be expanded to show its children. The items come from the ExpandableListAdapter associated with this view.

Example:
ExpandableListView example
ExpandableListView example

Create our custom MyBaseExpandableListAdapter extends BaseExpandableListAdapter, MyBaseExpandableListAdapter.java
package com.example.androidexpandablelistview;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter {
 
 private Context context;
    private List<String> listGroup;
    private HashMap<String, List<String>> listChild;

 public MyBaseExpandableListAdapter(Context c, List<String> lg,
            HashMap<String, List<String>> lc) {
  context = c;
  listGroup = lg;
  listChild = lc;
 }

 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return listChild.get(listGroup.get(groupPosition)).get(childPosition);
 }

 @Override
 public long getChildId(int groupPosition, int childPosition) {
  return childPosition;
 }

 @Override
 public View getChildView(int groupPosition, int childPosition, 
   boolean isLastChild, View convertView, ViewGroup parent) {
  
        if (convertView == null) {
            LayoutInflater infalInflater = 
              (LayoutInflater)context
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.item_layout, null);
        }
 
        TextView textViewItem = 
          (TextView)convertView.findViewById(R.id.item);
        
        String text = (String)getChild(groupPosition, childPosition);
 
        textViewItem.setText(text);
        return convertView;
 }

 @Override
 public int getChildrenCount(int groupPosition) {
  return listChild.get(listGroup.get(groupPosition)).size();
 }

 @Override
 public Object getGroup(int groupPosition) {
  return listGroup.get(groupPosition);
 }

 @Override
 public int getGroupCount() {
  return listGroup.size();
 }

 @Override
 public long getGroupId(int groupPosition) {
  return groupPosition;
 }

 @Override
 public View getGroupView(int groupPosition, 
   boolean isExpanded, View convertView, 
   ViewGroup parent) {
  
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater)context
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.group_layout, null);
        }
        
        String textGroup = (String)getGroup(groupPosition);
 
        TextView textViewGroup = (TextView)convertView.findViewById(R.id.group);
        textViewGroup.setText(textGroup);
 
        return convertView;
 }

 @Override
 public boolean hasStableIds() {
  return false;
 }

 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return true;
 }

}

/res/layout/group_layout.xml, layout of view of groups.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:orientation="vertical"
    android:padding="8dp" >

    <TextView
        android:id="@+id/group"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

</LinearLayout>

/res/layout/item_layout.xml, the layout of the view of children.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="italic" />

</LinearLayout>

/res/layout/activity_main.xml, main layout of our activity, with <ExpandableListView>.
<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=".MainActivity" >

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

    <ExpandableListView
        android:id="@+id/myexpandablelistview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java
package com.example.androidexpandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

public class MainActivity extends Activity {
 
 MyBaseExpandableListAdapter myBaseExpandableListAdapter;
    ExpandableListView myExpandableListView;
    List<String> myListForGroup;
    HashMap<String, List<String>> myMapForChild;
 

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  myExpandableListView = (ExpandableListView)
    findViewById(R.id.myexpandablelistview);
 
        initData();
 
        myBaseExpandableListAdapter = new 
          MyBaseExpandableListAdapter(this, myListForGroup, myMapForChild);
 
        myExpandableListView.setAdapter(myBaseExpandableListAdapter);
 }
 
 private void initData() {
  myListForGroup = new ArrayList<String>();
  myMapForChild = new HashMap<String, List<String>>();

        List<String> listGroupA = new ArrayList<String>();
        listGroupA.add("A - 1");
        listGroupA.add("A - 2");
        listGroupA.add("A - 3");

        List<String> listGroupB = new ArrayList<String>();
        listGroupB.add("B - 1");
 
        List<String> listGroupC = new ArrayList<String>();
        listGroupC.add("C - 1");
        listGroupC.add("C - 2");
        
        myListForGroup.add("Group A");
        myListForGroup.add("Group B");
        myListForGroup.add("Group C");
        
        myMapForChild.put(myListForGroup.get(0), listGroupA);
        myMapForChild.put(myListForGroup.get(1), listGroupB);
        myMapForChild.put(myListForGroup.get(2), listGroupC);
    }

}


Next: Detect user action on ExpandableListView, with various Listeners

Feb 15, 2014

android.text.TextUtils and android.text.Html

This example demonstrate how HTML encode/decode using android.text.TextUtils and android.text.Html.
HTML encode/decode
HTML encode/decode

package com.example.androidtextutils;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

 EditText textSrc;
 TextView textDest1, textDest2, textDest3, textDest4, textDest5;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textSrc = (EditText)findViewById(R.id.textsrc);
  textDest1 = (TextView)findViewById(R.id.textdest1);
  textDest2 = (TextView)findViewById(R.id.textdest2);
  textDest3 = (TextView)findViewById(R.id.textdest3);
  textDest4 = (TextView)findViewById(R.id.textdest4);
  textDest5 = (TextView)findViewById(R.id.textdest5);

  Button buttonConvert = (Button)findViewById(R.id.convert);
  buttonConvert.setOnClickListener(buttonConvertOnClickListener);
 }
 
 View.OnClickListener buttonConvertOnClickListener =
  new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    String src = (String) textSrc.getText().toString();
    String t_htmlEncode = TextUtils.htmlEncode(src);
    textDest1.setText(t_htmlEncode);
    Spanned t_htmlEncode_fromHtml = Html.fromHtml(t_htmlEncode);
    textDest2.setText(t_htmlEncode_fromHtml);
    
    Spanned t_fromHtml = Html.fromHtml(src);
    textDest3.setText(t_fromHtml);
    String t_fromHtml_toHtml = Html.toHtml(t_fromHtml);
    textDest4.setText(t_fromHtml_toHtml);
    
    String t_escapeHtml = Html.escapeHtml(src); //API 16
    textDest5.setText(t_escapeHtml);
   }};
 

}

<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="android-coding.blogspot.com" />

    <EditText
        android:id="@+id/textsrc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button 
        android:id="@+id/convert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Html-encode the string" />
    <TextView
        android:text="--- TextUtils.htmlEncode(src) ---"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textdest1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="--- Html.fromHtml(TextUtils.htmlEncode(src)) ---"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textdest2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="--- Html.fromHtml(src) ---"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textdest3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="--- Html.toHtml(Html.fromHtml(src)) ---"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textdest4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:text="--- Html.escapeHtml(src) ---"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textdest5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Feb 14, 2014

Html-encode string using TextUtils.htmlEncode()

TextUtils.htmlEncode(String s) Html-encode the string.

TextUtils.htmlEncode()
TextUtils.htmlEncode()

package com.example.androidtextutils;

import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

 EditText textSrc;
 TextView textDest;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textSrc = (EditText)findViewById(R.id.textsrc);
  textDest = (TextView)findViewById(R.id.textdest);
  Button buttonConvert = (Button)findViewById(R.id.convert);
  buttonConvert.setOnClickListener(buttonConvertOnClickListener);
 }
 
 View.OnClickListener buttonConvertOnClickListener =
  new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    String src = (String) textSrc.getText().toString();
    String dest = TextUtils.htmlEncode(src);
    textDest.setText(dest);
   }};
 

}

<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="android-coding.blogspot.com" />

    <EditText
        android:id="@+id/textsrc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button 
        android:id="@+id/convert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Html-encode the string" />
    <TextView
        android:id="@+id/textdest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


More example of using android.text.TextUtils and android.text.Html

Feb 8, 2014

Example of using TextUtils.commaEllipsize()

TextUtils.commaEllipsize() converts a CharSequence of the comma-separated form "Andy, Bob, Charles, David" that is too wide to fit into the specified width into one like "Andy, Bob, 2 more".

Here is a example:
TextUtils.commaEllipsize() example
TextUtils.commaEllipsize() example
  • When updateEllipsizedText() called in onCreate() to update myText1, because the views have not been shown here, getMeasuredWidth() inside updateEllipsizedText() return 0, so nothing shown on myText1.
  • To update myText2 after views layout, implement OnGlobalLayoutListener() to call updateEllipsizedText().

package com.example.androidtextutils;

import android.os.Bundle;
import android.app.Activity;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  final TextView myText1 = (TextView) findViewById(R.id.mytext1);
  final TextView myText2 = (TextView) findViewById(R.id.mytext2);

  final String days = "Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday";
  
  //views not yet layouted, getMeasuredWidth() inside updateEllipsizedText() return 0
  //nothing display on myText1!
  updateEllipsizedText(myText1, days);

  //update myText2 with TextUtils.commaEllipsize() String after layouted
  ViewTreeObserver viewTreeObserver = myText2.getViewTreeObserver();
  if (viewTreeObserver.isAlive()) {
   viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
       //removeGlobalOnLayoutListener() was deprecated in API level 16. 
       //Use removeOnGlobalLayoutListener() instead
       myText2.getViewTreeObserver().removeGlobalOnLayoutListener(this);
       //for API 16
       //myText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
       updateEllipsizedText(myText2, days);
      }
     });
  }
 }

 private void updateEllipsizedText(TextView tv, String text) {
  TextPaint p = tv.getPaint();
  tv.setText(text);
  float avail = tv.getMeasuredWidth();
  String oneMore = "one more";
  String more = "%d more";
  CharSequence ellipsizedText = TextUtils.commaEllipsize(text, p, avail,
    oneMore, more);
  tv.setText(ellipsizedText);
 }

}

<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="android-coding.blogspot.com" />

    <TextView
        android:id="@+id/mytext1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/mytext2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic" />

</LinearLayout>

Feb 4, 2014

Load image from resource ID using ImageManager

com.google.android.gms.common.images.ImageManager is a class in Google Play Services API, used to load images from the network and handles local caching. This example load images from resource ID using ImageManager.

Load image from resource ID using ImageManager
Load image from resource ID using ImageManager
- Before use Google Play Service API, you have to Set Up Google Play Services SDK.

-  Referencing a Google Play Service Library Project in your project, read here.

- Add <meta-data> of Google Play services library as a dependency as a child of the <application> in AndroidManifest.xml.
        <meta-data android:name="com.google.android.gms.version" 
            android:value="@integer/google_play_services_version" />

Example code:

- MainActivity.java
package com.example.androidloadimage;

import com.google.android.gms.common.images.ImageManager;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ImageView image1 = (ImageView)findViewById(R.id.image1);
  ImageView image2 = (ImageView)findViewById(R.id.image2);
  ImageView image3 = (ImageView)findViewById(R.id.image3);
  
  ImageManager imageManager = ImageManager.create(MainActivity.this);
  imageManager.loadImage(image1, R.drawable.ic_launcher);
  imageManager.loadImage(image2, android.R.drawable.ic_dialog_map);
  imageManager.loadImage(image3, R.drawable.common_signin_btn_icon_light);

 }

}

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/image2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Load image from internet, in AsyncTask

This example show how to load image from internet, in background thread using AsyncTask.

Load image from internet
Load image from internet
- First of all, to access internet from your app, you have to modify AndroidManifest.xml to add:
<uses-permission android:name="android.permission.INTERNET"/>

- You cannot access Network in main thread, otherwise error of "android.os.NetworkOnMainThreadException" will be reported. That's why we have to implement AsyncTask to load image in background thread.

- Once image loaded, update UI in main thread (or called UI Thread) in onPostExecute() method.

Example code:
package com.example.androidloadimage;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {
 
 String targetUrl = "http://goo.gl/qfGTN3";
 ImageView image1;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  image1 = (ImageView)findViewById(R.id.image1);
  
  /*
   * error Caused by: android.os.NetworkOnMainThreadException
   * if you access internet in Main Thread here!
   */
  //Bitmap bmLoadedImage = loadImageFromUrl(targetUrl);
  //image1.setImageBitmap(bmLoadedImage);
  
  new LoadImageTask(image1).execute(targetUrl);

 }
 
 private class LoadImageTask extends AsyncTask<String, Void, Bitmap>{
  
  ImageView targetImageView;
  
  LoadImageTask(ImageView iv){
   targetImageView = iv;
  }

  @Override
  protected Bitmap doInBackground(String... params) {
   Bitmap bm = loadImageFromUrl(params[0]);
   return bm;
  }

  @Override
  protected void onPostExecute(Bitmap result) {
   targetImageView.setImageBitmap(result);
  }
  
 }
 
 private Bitmap loadImageFromUrl(String targetUrl){
  Bitmap bm = null;
  
  try {
   URL url = new URL(targetUrl);
   URLConnection connection = url.openConnection();
   InputStream inputStream = connection.getInputStream();
   bm = BitmapFactory.decodeStream(inputStream);
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
  return bm;
 }

}

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Infolinks In Text Ads