<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TechieDreams</title>
	<atom:link href="/tag/android/feed/" rel="self" type="application/rss+xml" />
	<link>https://techiedreams.com</link>
	<description>find stuff related to: Android, AngularJS, Gulp, Bower, Yeoman...</description>
	<lastBuildDate>Fri, 30 Jan 2015 07:36:46 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.9.3</generator>
	<item>
		<title>Android Flickr Search with pagination.</title>
		<link>https://techiedreams.com/android-flickr-search-with-pagination/</link>
		<comments>https://techiedreams.com/android-flickr-search-with-pagination/#comments</comments>
		<pubDate>Thu, 28 Nov 2013 16:47:40 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android gridview]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=700</guid>
		<description><![CDATA[<p>Flickr Search &#8211; Lets make a simple image search App using the Yahoo&#8217;s flickr API. Flickr provides an api to query for particular tag with multiple options and it returns results in multiple requested formats, we parse the result and put them in a GridView and one can tap the image to make it pop &#8230;<br/><a class="more-link" href="/android-flickr-search-with-pagination/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-flickr-search-with-pagination/">Android Flickr Search with pagination.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Flickr Search &#8211; Lets make a simple image search App using the Yahoo&#8217;s flickr API. Flickr provides an api to query for particular tag with multiple options and it returns results in multiple requested formats, we parse the result and put them in a GridView and one can tap the image to make it pop out  to fullscreen. For this tutorial we are not going to deal with only few essential options of the search API.</p>
<p>Here is the final search URL:</p>
<blockquote><p>&#8220;https://api.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=[API_KEY]&amp;tags=[tag]&amp;per_page=20&amp;page=[curPage]&amp;format=json&amp;nojsoncallback=1&#8242;;&#8221;</p></blockquote>
<p>&nbsp;</p>
<p>In the above URL we are mentioning that the items per page to be &#8217;20&#8242; using the &#8216;per_page&#8217; property. So initially we load the first 20 items then on scroll to the end of the list we will then request for next &#8217;20&#8242; and so on.</p>
<p>&nbsp;</p>
<p>Also Please refer:</p>
<p><a href="http://www.flickr.com/services/api/flickr.photos.search.html">http://www.flickr.com/services/api/flickr.photos.search.html</a></p>
<p><a href="http://www.flickr.com/services/api/explore/flickr.photos.search">http://www.flickr.com/services/api/explore/flickr.photos.search</a></p>
<p>&nbsp;</p>
<p>So now to build this URL we need API_KEY, tag and the page number(starts from 1). You can generate an API by applying through this link:</p>
<p><a href="http://www.flickr.com/services/apps/create/apply/ " target="_blank">http://www.flickr.com/services/apps/create/apply/ </a></p>
<p>Now we got our API key and the tag will be inputted by the user using an edit text and the current page is by default 1 and we increment it and query as we scroll down to the end of the list.</p>
<p>To make this tutorial simple, as i already covered GridView and pop out  to fullscreen animation on click of the image in previous tutorials, here i will just cover the flickr api.</p>
<p><a href="/android-custom-gridview-scalable-auto-adjusting-col-width/">https://techiedreams.com/android-custom-gridview-scalable-auto-adjusting-col-width/</a></p>
<p><a href="/android-custom-grid-view-with-zoom-in-animation-effect/">https://techiedreams.com/android-custom-grid-view-with-zoom-in-animation-effect/</a></p>
<p>&nbsp;</p>
<p>The result returned by the API for a successful query will not contain any image url, but we can built one using the details provided in the &#8216;photo&#8217; item:</p>
<blockquote><p>&#8220;http://farm[farmId].staticflickr.com/[serverId]/[photoId]_[secretId]_m.jpg&#8221;;</p></blockquote>
<p>&nbsp;</p>
<p>Note: &#8216;_m&#8217; at the end of the url is to get the medium sized image. Different sizes can be retrieved by chaining this value.</p>
<p>Check this URL for examples:  <a href="http://www.flickr.com/services/api/misc.urls.html">http://www.flickr.com/services/api/misc.urls.html</a></p>
<p>&nbsp;</p>
<p>First lets create an entity to hold each photo data:</p><pre class="crayon-plain-tag">import java.io.Serializable;

public class FlickrPhoto implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String id, owner, secret, server, farm, title, ispublic;

	public String getFarmId() {
		return farm;
	}

	public void setFarm(String farm) {
		this.farm = farm;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}

	public String getSecretId() {
		return secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	public String getServerId() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getIspublic() {
		return ispublic;
	}

	public void setIspublic(String ispublic) {
		this.ispublic = ispublic;
	}

}</pre><p>&nbsp;</p>
<p>As i hope that you gone though my previous tutorial regarding the GridView and animated fullscreen effect, We now directly jump in to the Parser class. Here how it looks like:</p><pre class="crayon-plain-tag">import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.td.flickrsearch.entity.FlickrPhoto;

public class FlickrParser {

	public static ArrayList&lt;FlickrPhoto&gt; getPhotos(String tag, int currentPage) {

		ArrayList&lt;FlickrPhoto&gt; photos = new ArrayList&lt;FlickrPhoto&gt;();

		ServerResponse sr = new ServerResponse();
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String finalResult = null;

		HttpGet httpGet = new HttpGet(Util.getSearchUrl(tag.replaceAll(" ", ""), currentPage));

		try {

			response = client.execute(httpGet);

			sr.setSuccess(false);
			sr.setErrorMessage(null);
			sr.setResponseString(null);

			Log.d("serverapi", "" + response.getStatusLine().getStatusCode());
			HttpEntity responseEntity = response.getEntity();

			if (responseEntity != null) {
				finalResult = EntityUtils.toString(responseEntity);
				Log.d("serverapi", "Response: " + finalResult);
				if (response.getStatusLine().getStatusCode() == 200) {
					sr.setSuccess(true);
					sr.setResponseString(finalResult);
				} else {
					sr.setErrorMessage(finalResult);
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {

			if (sr.getResponseString() == null)
				return photos;

			JSONObject photosObj = new JSONObject(sr.getResponseString()).getJSONObject("photos");

			JSONArray jArray = photosObj.getJSONArray("photo");

			for (int i = 0; i &lt; jArray.length(); i++) {

				JSONObject jObj = jArray.getJSONObject(i);

				FlickrPhoto photo = new FlickrPhoto();

				photo.setId(jObj.getString("id"));
				photo.setOwner(jObj.getString("owner"));
				photo.setServer(jObj.getString("server"));
				photo.setSecret(jObj.getString("secret"));
				photo.setFarm(jObj.getString("farm"));
				photo.setTitle(jObj.getString("title"));
				photo.setIspublic(jObj.getString("ispublic"));

				photos.add(photo);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return photos;
	}

}</pre><p>&nbsp;</p>
<p><span class="highlight-red">Note:</span> Do not forget to add these permissions in the Manifest.xml</p><pre class="crayon-plain-tag">&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
&lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt;
&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>Here&#8217;s the final output of the application:</p>
<p><img class="alignnone size-medium wp-image-704" src="/wp-content/uploads/2013/11/td_flickersearch_1-168x300.png" alt="td_flickersearch_1" width="168" height="300" />          <img class="alignnone size-medium wp-image-705" src="/wp-content/uploads/2013/11/td_flickersearch_2-168x300.png" alt="td_flickersearch_2" width="168" height="300" />            <img class="alignnone size-medium wp-image-706" src="/wp-content/uploads/2013/11/td_flickersearch_3-168x300.png" alt="td_flickersearch_3" width="168" height="300" /></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" alt="" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a href="/downloads/TD FlickrSearch.zip" target="_blank">TD FlickrSearch</a></p>
<p><strong><em>Subscribe like and stay tuned!</em></strong></p>
<p>&nbsp;</p>

<div class="wp_rp_wrap  wp_rp_plain" id="wp_rp_first"><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-578" data-post-type="none" ><a href="/android-custom-gridview-scalable-auto-adjusting-col-width/" class="wp_rp_title"> Android custom GridView scalable (auto adjusting col width).</a></li><li data-position="1" data-poid="in-594" data-post-type="none" ><a href="/custom-contacts-picker-with-images-filtering-indexed-scrolling/" class="wp_rp_title">Android custom contacts picker with images, filtering &#038; indexed scrolling.</a></li><li data-position="2" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="3" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="4" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="5" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li></ul></div></div>
<p>The post <a href="/android-flickr-search-with-pagination/">Android Flickr Search with pagination.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-flickr-search-with-pagination/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Gmail like &#8211; Flip animated Multi selection list view with action mode.</title>
		<link>https://techiedreams.com/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/</link>
		<comments>https://techiedreams.com/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/#comments</comments>
		<pubDate>Sat, 23 Nov 2013 11:03:24 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Listview]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=632</guid>
		<description><![CDATA[<p>Android Gmail App has a very beautiful and smooth multi selection list, where you can select multiple items and perform an action over the selected items. Here in this tutorial we are going to create a similar effect on custom list where we have a image and a title and on-click of the image it &#8230;<br/><a class="more-link" href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><em>Android Gmail App has a very beautiful and smooth multi selection list, where you can select multiple items and perform an action over the selected items</em>.</p>
<p>Here in this tutorial we are going to create a similar effect on custom list where we have a image and a title and on-click of the image it gets checked with a flip animation.</p>
<p>Also if you are new for creating a custom list please go through my previous tutorials:</p>
<p><a href="/android-simple-custom-list-views-with-examples/">https://techiedreams.com/android-simple-custom-list-views-with-examples/</a></p>
<p><strong>Note : </strong>In this tutorial i used ABS(Actionbar Sherlock) for the Actionbar and Actionmode to support older versions also. Please find the library in the download package import it and add it to the project.</p>
<p>Here&#8217;s how the final result looks like:</p>
<p><img class="alignnone size-medium wp-image-661" alt="td_an_p13_1" src="/wp-content/uploads/2013/11/td_an_p13_1-176x300.png" width="176" height="300" />              <img alt="td_an_p13_2" src="/wp-content/uploads/2013/11/td_an_p13_2-175x300.png" width="175" height="300" /></p>
<p>First thing prior jumping in to this tutorial you should know how this works.</p>
<p>1. We flip the image half way (to middle).</p>
<p>2. End of the animation we now have image view rotated 90<b>°</b> we can imagine it as a thin line.</p>
<p>3. Now its time to change the image to inverse of the previous (Ex: if unchecked image is showing we replace it with checked image).</p>
<p>4. Now we run the second animation to rotate it from middle to normal. Done!</p>
<p>Hope you gone thorough my <a href="/android-simple-custom-list-views-with-examples/">custom listview</a> tutorial and have the custom list running, now</p>
<p>1. Create two anim files in the &#8216;anim&#8217; folder of resources.</p>
<p><strong>a) to_middle.xml :</strong></p><pre class="crayon-plain-tag">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="1.0" /&gt;</pre><p><strong>b) from_middle.xml :</strong></p><pre class="crayon-plain-tag">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="1.0" /&gt;</pre><p>&nbsp;</p>
<p>Now Lets jump in to the Main list activity where we initialize the Adapter and set our list view. Here is how the MainActivity looks like:</p><pre class="crayon-plain-tag">import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockActivity implements OnItemClickListener {

	ListView lvMyList;
	ArrayList&lt;MyListItem&gt; listItems = new ArrayList&lt;MyListItem&gt;();
	ActionBar actionBar;
	MyListAdapter myListAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lvMyList = (ListView) findViewById(R.id.lvMyList);
		lvMyList.setOnItemClickListener(this);

		for (int i = 0; i &lt; 20; i++) {
			MyListItem item = new MyListItem();
			item.setTitle("Sample Title " + (i + 1));
			listItems.add(item);
		}

		myListAdapter = new MyListAdapter(this, listItems);
		lvMyList.setAdapter(myListAdapter);

	}

	@Override
	public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) {
		// show description

	}

	public static final class AnActionModeOfEpicProportions implements ActionMode.Callback {

		Context ctx;

		public AnActionModeOfEpicProportions(Context ctx) {
			this.ctx = ctx;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			menu.add("Delete").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add("Archive").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add("Mark unread").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add("Move").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add("Remove star").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

			Toast toast = null;

			ArrayList&lt;MyListItem&gt; selectedListItems = new ArrayList&lt;MyListItem&gt;();

			StringBuilder selectedItems = new StringBuilder();

			// get items selected
			for (MyListItem i : ((MainActivity) ctx).myListAdapter.mailList) {
				if (i.isChecked()) {
					selectedListItems.add(i);
					selectedItems.append(i.getTitle()).append(", ");
				}
			}

			if (item.getTitle().equals("Delete")) {
				// Delete
				toast = Toast.makeText(ctx, "Delete: " + selectedItems.toString(), Toast.LENGTH_SHORT);

			} else if (item.getTitle().equals("Archive")) {
				// Archive
				toast = Toast.makeText(ctx, "Archive: " + selectedItems.toString(), Toast.LENGTH_SHORT);

			} else if (item.getTitle().equals("Mark unread")) {
				// Mark unread
				toast = Toast.makeText(ctx, "Mark unread: " + selectedItems.toString(), Toast.LENGTH_SHORT);

			} else if (item.getTitle().equals("Move")) {
				// Move
				toast = Toast.makeText(ctx, "Move: " + selectedItems.toString(), Toast.LENGTH_SHORT);

			} else if (item.getTitle().equals("Remove star")) {
				// Remove star
				toast = Toast.makeText(ctx, "Remove star: " + selectedItems.toString(), Toast.LENGTH_SHORT);

			}
			if (toast != null) {
				toast.show();
			}
			mode.finish();
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			// Action mode is finished reset the list and 'checked count' also
			// set all the list items checked states to false
			((MainActivity) ctx).myListAdapter.checkedCount = 0;
			((MainActivity) ctx).myListAdapter.isActionModeShowing = false;
			// set list items states to false
			for (MyListItem item : ((MainActivity) ctx).listItems) {
				item.setIsChecked(false);
			}
			((MainActivity) ctx).myListAdapter.notifyDataSetChanged();
			Toast.makeText(ctx, "Action mode closed", Toast.LENGTH_SHORT).show();
		}
	}

}</pre><p>&nbsp;</p>
<p>Now, Lets jump in to the meat of the Application, The Adapter class:</p><pre class="crayon-plain-tag">import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.view.ActionMode;

public class MyListAdapter extends BaseAdapter {

	Context context;
	ArrayList&lt;MyListItem&gt; mailList;
	Animation animation1;
	Animation animation2;
	ImageView ivFlip;
	int checkedCount = 0;
	ActionMode mMode;
	boolean isActionModeShowing;

	public MyListAdapter(Context context, ArrayList&lt;MyListItem&gt; mailList) {
		this.context = context;
		this.mailList = mailList;

		animation1 = AnimationUtils.loadAnimation(context, R.anim.to_middle);
		animation2 = AnimationUtils.loadAnimation(context, R.anim.from_middle);

		isActionModeShowing = false;
	}

	@Override
	public int getCount() {
		return mailList.size();
	}

	@Override
	public MyListItem getItem(int position) {
		return mailList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;

		LayoutInflater inflater = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.list_item, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView.findViewById(R.id.title);
			holder.selectBox = (ImageView) convertView.findViewById(R.id.selectBox);
			convertView.setTag(holder);
		}

		holder = (ViewHolder) convertView.getTag();

		holder.title.setText(getItem(position).getTitle());
		holder.selectBox.setTag("" + position);
		holder.selectBox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ivFlip = (ImageView) v;
				ivFlip.clearAnimation();
				ivFlip.setAnimation(animation1);
				ivFlip.startAnimation(animation1);
				setAnimListners(mailList.get(Integer.parseInt(v.getTag().toString())));
			}

		});

		if (mailList.get(position).isChecked()) {
			holder.selectBox.setImageResource(R.drawable.cb_checked);
			convertView.setBackgroundColor(context.getResources().getColor(R.color.list_highlight));

		} else {
			holder.selectBox.setImageResource(R.drawable.cb_unchecked);
			convertView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.list_selector));

		}

		return convertView;

	}

	private void setAnimListners(final MyListItem curMail) {
		AnimationListener animListner;
		animListner = new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				if (animation == animation1) {
					if (curMail.isChecked()) {
						ivFlip.setImageResource(R.drawable.cb_unchecked);
					} else {
						ivFlip.setImageResource(R.drawable.cb_checked);
					}
					ivFlip.clearAnimation();
					ivFlip.setAnimation(animation2);
					ivFlip.startAnimation(animation2);
				} else {
					curMail.setIsChecked(!curMail.isChecked());
					setCount();
					setActionMode();
				}
			}

			// Set selected count
			private void setCount() {
				if (curMail.isChecked()) {
					checkedCount++;
				} else {
					if (checkedCount != 0) {
						checkedCount--;
					}
				}

			}

			// Show/Hide action mode
			private void setActionMode() {
				if (checkedCount &gt; 0) {
					if (!isActionModeShowing) {
						mMode = ((MainActivity) context).startActionMode(new MainActivity.AnActionModeOfEpicProportions(context));
						isActionModeShowing = true;
					}
				} else if (mMode != null) {
					mMode.finish();
					isActionModeShowing = false;
				}

				// Set action mode title
				if (mMode != null)
					mMode.setTitle(String.valueOf(checkedCount));

				notifyDataSetChanged();

			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub

			}
		};

		animation1.setAnimationListener(animListner);
		animation2.setAnimationListener(animListner);

	}

	static class ViewHolder {
		TextView title;
		ImageView selectBox;
	}

}</pre><p>&nbsp;</p>
<p>MyListItem is an Entity where it holds the list items Name and Checked state. Here how it looks:</p><pre class="crayon-plain-tag">public class MyListItem {

	private String name;
	private boolean isChecked = false;

	public boolean isChecked() {
		return isChecked;
	}

	public void setIsChecked(boolean isChecked) {
		this.isChecked = isChecked;
	}

	public String getTitle() {
		return name;
	}

	public void setTitle(String name) {
		this.name = name;
	}
}</pre><p>&nbsp;</p>
<p><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /> <strong>Download Sources:</strong></p>
<p class="lang:default highlight:0 decode:true"><a href="/downloads/TD FlipMultiselectList.zip" target="_blank">TD Flip Multiselect List</a></p>
<p class="lang:default highlight:0 decode:true"><strong><em>Subscribe like and stay tuned!</em></strong></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="1" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="2" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="3" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="4" data-poid="in-700" data-post-type="none" ><a href="/android-flickr-search-with-pagination/" class="wp_rp_title">Android Flickr Search with pagination.</a></li><li data-position="5" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li></ul></div></div>
<p>The post <a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Android custom contacts picker with images, filtering &amp; indexed scrolling.</title>
		<link>https://techiedreams.com/custom-contacts-picker-with-images-filtering-indexed-scrolling/</link>
		<comments>https://techiedreams.com/custom-contacts-picker-with-images-filtering-indexed-scrolling/#comments</comments>
		<pubDate>Sun, 30 Jun 2013 04:49:07 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Andorid contacts picker]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=594</guid>
		<description><![CDATA[<p>This custom contact picker allows you to pick one or more contacts so that you can use them of any purposes like sending a mail, using their email Id&#8217;s or phone numbers etc. Her am going to use a custom listview to load all the contacts form the Phone and the each item is provided &#8230;<br/><a class="more-link" href="/custom-contacts-picker-with-images-filtering-indexed-scrolling/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/custom-contacts-picker-with-images-filtering-indexed-scrolling/">Android custom contacts picker with images, filtering &#038; indexed scrolling.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>This custom contact picker allows you to pick one or more contacts so that you can use them of any purposes like sending a mail, using their email Id&#8217;s or phone numbers etc.</p>
<p>Her am going to use a custom listview to load all the contacts form the Phone and the each item is provided with a check box to select.</p>
<p>Please go through the Custom list view post if you don&#8217;t know how to create. &#8211; https://techiedreams.com/android-simple-custom-list-views-with-examples/</p>
<p>The next we need to know is hoe to fetch the contacts from the Phone:</p>
<p>1. All the contacts in the phone are stored in data base organized by their types. We need to find our required URI to query through and get the desired results. One we have the URI we can query on that using content resolver we need to specify the required columns that need to loaded before querying which helps speeding up the query time.</p>
<p>Here is our cursor from which we will extracts all the contacts information:</p><pre class="crayon-plain-tag">Cursor cur = getContentResolver().query(Data.CONTENT_URI, new String[] { Data.CONTACT_ID, Data.MIMETYPE, Email.ADDRESS,
Contacts.DISPLAY_NAME, Phone.NUMBER }, null, null, Contacts.DISPLAY_NAME);</pre><p>&nbsp;</p>
<p>This is the out put we will get:<br />
<img class="alignnone size-medium wp-image-603" alt="contcats_picker_all" src="/wp-content/uploads/2013/06/contcats_picker_all.png" width="600" height="1039" /></p>
<p>First create a Simple POJO for Contact and it should implement Parcelable &#8211; Contact.java:</p><pre class="crayon-plain-tag">public class Contact implements Parcelable {

private String contactName;
private String contactNumber;
private Bitmap contactPhoto;
private Uri contactPhotoUri;
private String contactEmail;

boolean selected = false;

public Contact() {
;
}

public String getContactName() {
return contactName;
}

public String getContactNumber() {
return contactNumber;
}

public Bitmap getContactPhoto() {
return contactPhoto;
}

public Uri getContactPhotoUri() {
return contactPhotoUri;
}

public void setContactName(String contactName) {
this.contactName = contactName;
}

public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}

public void setContactPhoto(Bitmap contactPhoto) {
this.contactPhoto = contactPhoto;

}

public void setContactPhotoUri(Uri contactPhotoUri) {
this.contactPhotoUri = contactPhotoUri;
}

public String getContactEmail() {
return contactEmail;
}

public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

@Override
public int describeContents() {
return 0;
}

@Override
public String toString() {
return contactName + " " + contactNumber + " ";
}

@Override
public void writeToParcel(Parcel dest, int flags) {

dest.writeString(contactName);
dest.writeString(contactNumber);
dest.writeString(contactPhotoUri.toString());
dest.writeString(contactEmail);

}

public Contact(Parcel source) {

contactName = source.readString();
contactNumber = source.readString();
contactPhotoUri = Uri.parse(source.readString());
contactEmail = source.readString();
}

public static final Parcelable.Creator&lt;Contact&gt; CREATOR = new Parcelable.Creator&lt;Contact&gt;() {

@Override
public Contact createFromParcel(Parcel source) {
return new Contact(source);
}

@Override
public Contact[] newArray(int size) {
return new Contact[size];
}

};

}</pre><p>&nbsp;</p>
<p>Next add these permissions and activity to your manifest. The final manifest file will look like this:</p><pre class="crayon-plain-tag">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.td.contactpicker"
android:versionCode="1"
android:versionName="1.0" &gt;

&lt;uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" /&gt;

&lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
&lt;uses-permission android:name="android.permission.READ_CONTACTS" /&gt;

&lt;application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" &gt;
&lt;activity
android:name="com.td.contactpicker.ContactManager"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" &gt;
&lt;intent-filter&gt;
&lt;action android:name="android.intent.action.MAIN" /&gt;

&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;

&lt;/manifest&gt;</pre><p>&nbsp;</p>
<p>Now we have to create the main contact picker class. Lets name it as &#8216;ContactManager.java&#8217;. Here the final class will look like. It is self explained through comments:</p><pre class="crayon-plain-tag">public final class ContactManager extends Activity {

private static ArrayList&lt;Contact&gt; contacts = null;
private LinkedHashMap&lt;String, Contact&gt; allContacts = new LinkedHashMap&lt;String, Contact&gt;();
private ContactAdapter contactAdapter = null;
private ListView lv;
ImageView doneSelect;
RelativeLayout progressLayout;
EditText myFilter;

// Indexing fo the list
HashMap&lt;String, Integer&gt; alphaIndexer;
String[] sections;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_manager);

// /////////// Custom progress Layout //////////////////////
progressLayout = (RelativeLayout) findViewById(R.id.progress_layout);

progressLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
progressLayout.setVisibility(View.GONE); // by default progress view to GONE
// /////////////////////////////////////

// Init UI elements
lv = (ListView) findViewById(R.id.contactList);
doneSelect = (ImageView) findViewById(R.id.doneSelect);
myFilter = (EditText) findViewById(R.id.search_txt);

// Register handler for UI elements
doneSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Util.hideSoftKeyboard(ContactManager.this);
setSelctedcontacts();
}

});

// Add text listner to the edit text for filtering the List
myFilter.addTextChangedListener(new TextWatcher() {

@Override
public void afterTextChanged(Editable s) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// call the filter with the current text on the editbox
contactAdapter.getFilter().filter(s.toString());
}
});

if (contacts == null) {
contacts = new ArrayList&lt;Contact&gt;();
// Asynchronously load all contacts
new AsyncLoadContacts().execute();
} else {
contactAdapter = new ContactAdapter(this, R.id.contactList, contacts);
lv.setAdapter(contactAdapter);

}

}

// set selected contacts on DONE button press
private void setSelctedcontacts() {

ArrayList&lt;Contact&gt; selectedList = new ArrayList&lt;Contact&gt;();

Intent intent = new Intent();

ArrayList&lt;Contact&gt; contactList = contactAdapter.originalList;
for (int i = 0; i &lt; contactList.size(); i++) {
Contact contact = contactList.get(i);
if (contact.isSelected()) {
selectedList.add(contact);
}
if (selectedList.size() &gt; 0) {
intent.putParcelableArrayListExtra("SELECTED_CONTACTS", selectedList);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED, intent);
}
}
// Tip: Here you can finish this activity and on the Activty result of the calling activity you fetch the Selected contacts

}

// Also on back pressed set the selected list, if nothing selected set Intent result to canceled
@Override
public void onBackPressed() {

ArrayList&lt;Contact&gt; selectedList = new ArrayList&lt;Contact&gt;();

Intent intent = new Intent();

ArrayList&lt;Contact&gt; contactList = contactAdapter.originalList;
for (int i = 0; i &lt; contactList.size(); i++) {
Contact contact = contactList.get(i);
if (contact.isSelected()) {
selectedList.add(contact);
}
if (selectedList.size() &gt; 0) {
intent.putParcelableArrayListExtra("SELECTED_CONTACTS", selectedList);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED, intent);
}
}

finish();

};

@SuppressLint("InlinedApi")
private void getContacts() {

ContentResolver cr = getContentResolver();

Cursor cur = cr.query(Data.CONTENT_URI, new String[] { Data.CONTACT_ID, Data.MIMETYPE, Email.ADDRESS,
Contacts.DISPLAY_NAME, Phone.NUMBER }, null, null, Contacts.DISPLAY_NAME);

Contact contact;

if (cur.getCount() &gt; 0) {

while (cur.moveToNext()) {

String id = cur.getString(cur.getColumnIndex(Data.CONTACT_ID));

String mimeType = cur.getString(cur.getColumnIndex(Data.MIMETYPE));

if (allContacts.containsKey(id)) {
// update contact
contact = allContacts.get(id);
} else {
contact = new Contact();
allContacts.put(id, contact);
// set photoUri
contact.setContactPhotoUri(getContactPhotoUri(Long.parseLong(id)));
}

if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE))
// set name
contact.setContactName(cur.getString(cur.getColumnIndex(Contacts.DISPLAY_NAME)));

if (mimeType.equals(Phone.CONTENT_ITEM_TYPE))
// set phone munber
contact.setContactNumber(cur.getString(cur.getColumnIndex(Phone.NUMBER)));

if (mimeType.equals(Email.CONTENT_ITEM_TYPE))
// set email
contact.setContactEmail(cur.getString(cur.getColumnIndex(Email.ADDRESS)));

}
}

cur.close();
// get contacts from hashmap
contacts.clear();
contacts.addAll(allContacts.values());

// remove slef contact
for (Contact _contact : contacts) {

if (_contact.getContactName() == null &amp;&amp; _contact.getContactNumber() == null
&amp;&amp; _contact.getContactEmail() == null) {
contacts.remove(_contact);
break;
}

}

contactAdapter = new ContactAdapter(this, R.id.contactList, contacts);
contactAdapter.notifyDataSetChanged();

}

// Get contact photo URI for contactId
public Uri getContactPhotoUri(long contactId) {
Uri photoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
photoUri = Uri.withAppendedPath(photoUri, Contacts.Photo.CONTENT_DIRECTORY);
return photoUri;
}

private class AsyncLoadContacts extends AsyncTask&lt;Void, Void, Void&gt; {

@Override
protected void onPreExecute() {

progressLayout.setVisibility(View.VISIBLE);
}

@Override
protected Void doInBackground(Void... params) {

// Obtain contacts
getContacts();
return null;

}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

// set contact adapter
lv.setAdapter(contactAdapter);

// set the progress to GONE
progressLayout.setVisibility(View.GONE);
}

}

// Contact adapter
public class ContactAdapter extends ArrayAdapter&lt;Contact&gt; implements SectionIndexer {

private ArrayList&lt;Contact&gt; contactList;
private ArrayList&lt;Contact&gt; originalList;
private ContactFilter filter;

public ContactAdapter(Context context, int textViewResourceId, ArrayList&lt;Contact&gt; items) {
super(context, textViewResourceId, items);

this.contactList = new ArrayList&lt;Contact&gt;();
this.originalList = new ArrayList&lt;Contact&gt;();

this.contactList.addAll(items);
this.originalList.addAll(items);

// indexing
alphaIndexer = new HashMap&lt;String, Integer&gt;();
int size = contactList.size();

for (int x = 0; x &lt; size; x++) {
String s = contactList.get(x).getContactName();

// get the first letter of the store
String ch = s.substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();

// HashMap will prevent duplicates
alphaIndexer.put(ch, x);
}

Set&lt;String&gt; sectionLetters = alphaIndexer.keySet();

// create a list from the set to sort
ArrayList&lt;String&gt; sectionList = new ArrayList&lt;String&gt;(sectionLetters);

Collections.sort(sectionList);

sections = new String[sectionList.size()];

sectionList.toArray(sections);
}

@Override
public Filter getFilter() {
if (filter == null) {
filter = new ContactFilter();
}
return filter;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;

if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.contact_item, null);
}
final Contact contact = contactList.get(position);
if (contact != null) {
TextView name = (TextView) view.findViewById(R.id.name);
ImageView thumb = (ImageView) view.findViewById(R.id.thumb);
TextView number = (TextView) view.findViewById(R.id.number);
TextView email = (TextView) view.findViewById(R.id.email);

// labels
TextView numberLabel = (TextView) view.findViewById(R.id.numberLabel);
TextView emailLabel = (TextView) view.findViewById(R.id.emailLabel);

thumb.setImageURI(contact.getContactPhotoUri());

if (thumb.getDrawable() == null)
thumb.setImageResource(R.drawable.def_contact);

final CheckBox nameCheckBox = (CheckBox) view.findViewById(R.id.checkBox);

name.setText(contact.getContactName());

// set number label
if (contact.getContactNumber() == null)
numberLabel.setText("");
else
numberLabel.setText("P: ");

number.setText(contact.getContactNumber());

if (contact.getContactEmail() == null)
emailLabel.setText("");
else
emailLabel.setText("E: ");

email.setText(contact.getContactEmail());

nameCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

contact.setSelected(nameCheckBox.isChecked());
}
});

nameCheckBox.setChecked(contact.isSelected());
}

return view;
}

@Override
public int getPositionForSection(int section) {
return alphaIndexer.get(sections[section]);
}

@Override
public int getSectionForPosition(int position) {
return 0;
}

@Override
public Object[] getSections() {
return sections;
}

// Contacts filter
private class ContactFilter extends Filter {

@Override
protected FilterResults performFiltering(CharSequence constraint) {

constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null &amp;&amp; constraint.toString().length() &gt; 0) {
ArrayList&lt;Contact&gt; filteredItems = new ArrayList&lt;Contact&gt;();

for (int i = 0, l = originalList.size(); i &lt; l; i++) {
Contact contact = originalList.get(i);
if (contact.toString().toLowerCase().contains(constraint))
filteredItems.add(contact);
}
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}

@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {

contactList = (ArrayList&lt;Contact&gt;) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = contactList.size(); i &lt; l; i++)
add(contactList.get(i));
notifyDataSetInvalidated();
}
}

}

}</pre><p>&nbsp;</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a href="/downloads/TD ContactsPicker.zip"><strong>TD Contacts picker </strong></a></p>
<p><strong><em>Subscribe like and stay tuned!</em></strong></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-700" data-post-type="none" ><a href="/android-flickr-search-with-pagination/" class="wp_rp_title">Android Flickr Search with pagination.</a></li><li data-position="1" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="2" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="3" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="4" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="5" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li></ul></div></div>
<p>The post <a href="/custom-contacts-picker-with-images-filtering-indexed-scrolling/">Android custom contacts picker with images, filtering &#038; indexed scrolling.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/custom-contacts-picker-with-images-filtering-indexed-scrolling/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Android custom GridView scalable (auto adjusting col width).</title>
		<link>https://techiedreams.com/android-custom-gridview-scalable-auto-adjusting-col-width/</link>
		<comments>https://techiedreams.com/android-custom-gridview-scalable-auto-adjusting-col-width/#comments</comments>
		<pubDate>Sun, 05 May 2013 15:44:50 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android gridview]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=578</guid>
		<description><![CDATA[<p>Its all ways digusting me when using Android grid view because the cols are not free flowing even though we set the cols to expand and the solution is we need to set the col width dynamically by calculating with the screen width to the number of cols drawn. This is what we are going &#8230;<br/><a class="more-link" href="/android-custom-gridview-scalable-auto-adjusting-col-width/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-custom-gridview-scalable-auto-adjusting-col-width/">Android custom GridView scalable (auto adjusting col width).</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Its all ways digusting me when using Android grid view because the cols are not free flowing even though we set the cols to expand and the solution is we need to set the col width dynamically by calculating with the screen width to the number of cols drawn.</p>
<p>This is what we are going to achieve:</p>
<p><img class="alignnone size-full wp-image-586" alt="tdgrid_s1" src="/wp-content/uploads/2013/05/tdgrid_s1.png" width="285" height="488" /></p>
<p><img class="alignnone size-full wp-image-585" alt="tdgrid_s2" src="/wp-content/uploads/2013/05/tdgrid_s2.png" width="503" height="269" /></p>
<p>Here is how it can be done:</p>
<p>Step 1: Create a new project and add GridView to main xml:</p><pre class="crayon-plain-tag">&lt;GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/albumGrid"
style="@style/PhotoGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/black"
android:columnWidth="@dimen/photo_size"
android:horizontalSpacing="@dimen/photo_spacing"
android:numColumns="auto_fit"
android:padding="4dp"
android:scrollbars="none"
android:stretchMode="columnWidth"
android:verticalSpacing="@dimen/photo_spacing" /&gt;</pre><p>&nbsp;</p>
<p>Step 2: Make your main activity exactly as below.</p>
<p>[The code below is self explained where ever required through comments].</p><pre class="crayon-plain-tag">public class MainActivity extends Activity {

private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private ImageAdapter imageAdapter;

// Some items to add to the GRID
private static final String[] CONTENT = new String[] { "Akon", "Justin Bieber", "AlRight", "Big Sean",
"Britney Spears", "Hilary", "Micheal Buble", "Akon", "Justin Bieber", "AlRight", "Big Sean",
"Britney Spears", "Hilary", "Micheal Buble", "Britney Spears", "Hilary", "Micheal Buble", "Akon",
"Justin Bieber", "AlRight", "Big Sean", "Britney Spears", "Hilary", "Micheal Buble", "Akon",
"Justin Bieber", "AlRight", "Big Sean", "Britney Spears", "Hilary", "Micheal Buble", "Akon",
"Justin Bieber", "AlRight", "Big Sean", "Britney Spears", "Hilary", "Micheal Buble", "Britney Spears",
"Hilary", "Micheal Buble", "Akon", "Justin Bieber", "AlRight", "Big Sean", "Britney Spears", "Hilary",
"Micheal Buble" };
private static final int[] ICONS = new int[] { R.drawable.cover_akon, R.drawable.cover_justin,
R.drawable.cover_alright, R.drawable.cover_big_sean, R.drawable.cover_britney, R.drawable.cover_hilary,
R.drawable.cover_mb, R.drawable.cover_akon, R.drawable.cover_justin, R.drawable.cover_alright,
R.drawable.cover_big_sean, R.drawable.cover_britney, R.drawable.cover_hilary, R.drawable.cover_mb,
R.drawable.cover_britney, R.drawable.cover_hilary, R.drawable.cover_mb, R.drawable.cover_akon,
R.drawable.cover_justin, R.drawable.cover_alright, R.drawable.cover_big_sean, R.drawable.cover_britney,
R.drawable.cover_hilary, R.drawable.cover_mb, R.drawable.cover_akon, R.drawable.cover_justin,
R.drawable.cover_alright, R.drawable.cover_big_sean, R.drawable.cover_britney, R.drawable.cover_hilary,
R.drawable.cover_mb, R.drawable.cover_akon, R.drawable.cover_justin, R.drawable.cover_alright,
R.drawable.cover_big_sean, R.drawable.cover_britney, R.drawable.cover_hilary, R.drawable.cover_mb,
R.drawable.cover_britney, R.drawable.cover_hilary, R.drawable.cover_mb, R.drawable.cover_akon,
R.drawable.cover_justin, R.drawable.cover_alright, R.drawable.cover_big_sean, R.drawable.cover_britney,
R.drawable.cover_hilary, R.drawable.cover_mb };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// get the photo size and spacing
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);

// initialize image adapter
imageAdapter = new ImageAdapter();

photoGrid = (GridView) findViewById(R.id.albumGrid);

// set image adapter to the GridView
photoGrid.setAdapter(imageAdapter);

// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns &gt; 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);

}
}
}
});
}

// ///////// ImageAdapter class /////////////////
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;

public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}

public int getCount() {
return CONTENT.length;
}

// set numcols
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}

public int getNumColumns() {
return mNumColumns;
}

// set photo item height
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
notifyDataSetChanged();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(final int position, View view, ViewGroup parent) {

if (view == null)
view = mInflater.inflate(R.layout.photo_item, null);

ImageView cover = (ImageView) view.findViewById(R.id.cover);
TextView title = (TextView) view.findViewById(R.id.title);

cover.setLayoutParams(mImageViewLayoutParams);

// Check the height matches our calculated column width
if (cover.getLayoutParams().height != mItemHeight) {
cover.setLayoutParams(mImageViewLayoutParams);
}

cover.setImageResource(ICONS[position % ICONS.length]);
title.setText(CONTENT[position % CONTENT.length]);

return view;
}
}

}</pre><p>&nbsp;</p>
<p>Step 3: Add these files to the values folder:</p>
<p>colors.xml :</p><pre class="crayon-plain-tag">&lt;resources&gt;

&lt;color name="grid_state_pressed"&gt;#BB561e14&lt;/color&gt;
&lt;color name="grid_state_focused"&gt;#77561e14&lt;/color&gt;
&lt;color name="transparent"&gt;#00000000&lt;/color&gt;
&lt;color name="white"&gt;#fff&lt;/color&gt;
&lt;color name="black"&gt;#000&lt;/color&gt;

&lt;/resources&gt;</pre><p>&nbsp;</p>
<p>dimens.xml :</p><pre class="crayon-plain-tag">&lt;resources&gt;

&lt;dimen name="photo_size"&gt;120dp&lt;/dimen&gt;
&lt;dimen name="photo_spacing"&gt;4dp&lt;/dimen&gt;

&lt;/resources&gt;</pre><p>&nbsp;</p>
<p>styles.xml :</p><pre class="crayon-plain-tag">&lt;resources&gt;

&lt;!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
--&gt;
&lt;style name="AppBaseTheme" parent="android:Theme.Light"&gt;
&lt;!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
--&gt;
&lt;/style&gt;

&lt;!-- Application theme. --&gt;
&lt;style name="AppTheme" parent="AppBaseTheme"&gt;
&lt;!-- All customizations that are NOT specific to a particular API-level can go here. --&gt;
&lt;/style&gt;

&lt;style name="PhotoGrid"&gt;
&lt;item name="android:drawSelectorOnTop"&gt;true&lt;/item&gt;
&lt;item name="android:listSelector"&gt;@drawable/photogrid_selector&lt;/item&gt;
&lt;/style&gt;

&lt;/resources&gt;</pre><p>&nbsp;</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a title="https://techiedreams.com/downloads/TD%20GridView.zip" href="/downloads/TD%20GridView.zip"><strong>TD GridView </strong></a></p>
<p><em><strong>Subscribe like and stay tuned!</strong></em></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-700" data-post-type="none" ><a href="/android-flickr-search-with-pagination/" class="wp_rp_title">Android Flickr Search with pagination.</a></li><li data-position="1" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="2" data-poid="in-240" data-post-type="none" ><a href="/android-layouts-explained-with-examples/" class="wp_rp_title">Android Layouts explained with examples.</a></li><li data-position="3" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="4" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li><li data-position="5" data-poid="in-186" data-post-type="none" ><a href="/activity-and-its-life-cycle/" class="wp_rp_title">Android Activity and its Life Cycle.</a></li></ul></div></div>
<p>The post <a href="/android-custom-gridview-scalable-auto-adjusting-col-width/">Android custom GridView scalable (auto adjusting col width).</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-custom-gridview-scalable-auto-adjusting-col-width/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</title>
		<link>https://techiedreams.com/android-rss-reader-part-3-action-bar-with-animated-item/</link>
		<comments>https://techiedreams.com/android-rss-reader-part-3-action-bar-with-animated-item/#comments</comments>
		<pubDate>Sun, 09 Dec 2012 19:15:28 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[ActionBar Animaton]]></category>
		<category><![CDATA[RSS Reader]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=493</guid>
		<description><![CDATA[<p>This is in continuation with the RSS Reader Part 2 in the RSS Reader Series. In this tutorial we will introduce the &#8216;ActionBar&#8217; and have a refresh item which refreshes the List with a rotating animation effect, a share action bar item in the description view to share the the news. Here&#8217;s the video demo &#8230;<br/><a class="more-link" href="/android-rss-reader-part-3-action-bar-with-animated-item/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-rss-reader-part-3-action-bar-with-animated-item/">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><em><strong>T</strong>his is in continuation with the <a title="https://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" target="_blank">RSS Reader Part 2</a> in the RSS Reader Series. In this tutorial we will introduce the &#8216;ActionBar&#8217; and have a refresh item which refreshes the List with a rotating animation effect, a share action bar item in the description view to share the the news. Here&#8217;s the video demo of this tutorial:</em></p>
<p><iframe width="610" height="350" src="http://www.youtube.com/embed/R_qR2glTTAs" frameborder="0"></iframe></p>
<p><span class="highlight-red">Note</span>: Please note that you cant test the share functionality in the emulator so find a device running API 14+.<br />
here a bug reported on the same: <a title="http://code.google.com/p/android/issues/detail?id=25467" href="http://code.google.com/p/android/issues/detail?id=25467" target="_blank">http://code.google.com/p/android/issues/detail?id=25467</a></p>
<p>&#8216;ActionBar&#8217; will be shown by default when you are running your app built with SDK (API Level 11 +)  on the compatible emulator or the device.</p>
<p>So lets first start with adding the Items to the &#8216;ActionBar&#8217;. In the List Activity we have two Action bar items they are 1. Refresh and 2. About.</p>
<p><img title="rss-reader-3-action-1" src="/wp-content/uploads/2012/12/rss-reader-3-action-1.png" alt="" width="331" height="47" /></p>
<p><span style="text-decoration: underline;"><strong>Steps in creating the Listview action items</strong></span>:</p>
<p><strong>step</strong> 1: Create a &#8216;menu&#8217; folder under the resources (res/menu). Create an xml file (activity_main.xml) with the following content:</p>
<p>activity_main.xml:</p><pre class="crayon-plain-tag">&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt;
&lt;item
android:id="@+id/refresh_option"
android:icon="@drawable/action_refresh"
android:showAsAction="ifRoom"
android:title="Refresh"/&gt;
&lt;item
android:id="@+id/about_option"
android:icon="@drawable/action_about"
android:showAsAction="ifRoom"
android:title="About Me"/&gt;
&lt;/menu&gt;</pre><p>Here you can see if the &#8216;showAsAction&#8217; for a Menu item is set then it will appear on the &#8216;Action Bar&#8217;. The option &#8216;ifRoom&#8217; tells the item that it should to be shown in ActionBar only when there is a room (space) or else it will be shown as a general Menu item.</p>
<p>Also refer: <a title="http://developer.android.com/design/patterns/actionbar.html" href="http://developer.android.com/design/patterns/actionbar.html" target="_blank">http://developer.android.com/design/patterns/actionbar.html</a></p>
<p><strong>step 2</strong>: Open the Activity (List Activity) in which we want to add these ActionBar items and add the following code:</p><pre class="crayon-plain-tag">@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return (super.onCreateOptionsMenu(menu));
}</pre><p>In the above code we are just inflating the menu views from the xml we just created. When we run the app now we can see the items added to the ActionBar.</p>
<p><strong>step 3</strong>: Now we need to implement those ActionBar items.</p>
<p>Here&#8217;s the method to implement the ActionBar items:</p><pre class="crayon-plain-tag">@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh_option:
refreshList(item);
return (true);

case R.id.about_option:
Toast.makeText(this, "RSS Reader!", Toast.LENGTH_SHORT).show();
return (true);

}
return super.onOptionsItemSelected(item);
}</pre><p>So in the above method we will returned with the item clicked and we will switch the id of the item and perform actions based on the item clicked.</p>
<p><strong>step 4</strong>: When the refresh item clicked, we first have to start the Animation followed by the feed refresh, then once after feed is refreshed and set, we need to stop the animation.</p>
<p>we achieve this by creating a method which takes in the Menu Item (Refresh Menu &#8211; Item) as an argument, and replacing this item with a custom view and applying the animation to that view. Bit tricky but you can get the full picture when you see the final code.</p>
<p><strong>step 5</strong>: So first we need to create a layout for the ActionBar item with just a ImageView hodling the refresh image:</p><pre class="crayon-plain-tag">&lt;ImageView xmlns:android="http://schemas.android.com/apk/res/android"
style="@android:style/Widget.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/action_refresh" /&gt;</pre><p><strong>step 6</strong>: Now we need to create a rotating animation, for this first lets create a folder called &#8216;anim&#8217; under resources (res/anim), then create a new xml file (refresh_rotate.xml) with the below content:</p><pre class="crayon-plain-tag">&lt;rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" /&gt;</pre><p><strong>step 7</strong>: Now in the refresh method we need to inflate the layout (action_refresh.xml) which we just created and set the animation to the layout then set the item view to the new animated View.</p><pre class="crayon-plain-tag">LayoutInflater inflater = (LayoutInflater) getApplication()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView) inflater.inflate(R.layout.action_refresh,
null);

Animation rotation = AnimationUtils.loadAnimation(getApplication(),
R.anim.refresh_rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);

item.setActionView(iv);</pre><p><strong>step 8</strong>: Ok, now that the animation view is set up and running we need to start the refresh process. In this post what i mean to refresh is nothing but getting the new feed from the URL and then setting the List back. So we start the refresh process (parsing) in a new thread and then after we get the new feed, we notify the adapter with the change, then the adapter will refresh the views with the new data.</p>
<p>The final refresh Method is here:</p><pre class="crayon-plain-tag">public void refreshList(final MenuItem item) {
/* Attach a rotating ImageView to the refresh item as an ActionView */
LayoutInflater inflater = (LayoutInflater) getApplication()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView) inflater.inflate(R.layout.action_refresh,
null);

Animation rotation = AnimationUtils.loadAnimation(getApplication(),
R.anim.refresh_rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);

item.setActionView(iv);

// trigger feed refresh:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
DOMParser tmpDOMParser = new DOMParser();
feed = tmpDOMParser.parseXml(feedLink);

ListActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
if (feed != null &amp;&amp; feed.getItemCount() &gt; 0) {
adapter.notifyDataSetChanged();
// lv.setAdapter(adapter);
item.getActionView().clearAnimation();
item.setActionView(null);
}
}
});
}
});
thread.start();
}</pre><p>We can&#8217;t notify the adapter with the change in the Background thread so first we create a UI thread and then call the &#8216;adapter.notifyDataSetChanged()&#8217; inside the thread. Once the list is updated we clear the animation and set the view to null.</p>
<p><span style="text-decoration: underline;"><strong>Now will move to the description view. In the description view we need to set these things</strong></span>:</p>
<p>1. Make the logo, on click take back to the List view.</p>
<p>2. Add a share ActionBar item.</p>
<p>Here&#8217;s the snapshot of the final picture:</p>
<p><img title="rss-reader-3-action-2" src="/wp-content/uploads/2012/12/rss-reader-3-action-2.png" alt="" width="331" height="48" /></p>
<p>So first lets make the logo as the navigation button which takes us back to the List View. Here is how we achieve this:</p>
<p><strong>step 1</strong>: Open the description activity and then add these two lines:</p><pre class="crayon-plain-tag">ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);</pre><p>In the above code we are just getting the ActionBar reference and then setting the setDisplayHomeAsUpEnabled(true).</p>
<p><strong>step 2</strong>: Not done yet, now we just made the ActionBar logo as the navigation button with a arrow marker shown to the left (Run the app and check for your understanding) but we need to add the implementation. Here&#8217;s how we add the implementation:</p><pre class="crayon-plain-tag">@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case android.R.id.home:
// app icon in action bar clicked; finish activity to go home
finish();
return true;
}
return super.onOptionsItemSelected(item);
}</pre><p><strong>step 3</strong>: When we set the &#8216;setDisplayHomeAsUpEnabled&#8217; to true and we press the logo in the description view, then the &#8216;onOptionsItemSelected&#8217; method method will be invoked with the id: android.R.id.home. So we check for the id and in the implementation we simply finish the activity to go back to the List view.</p>
<p><strong>Finally now we need to have a share Action item to share the particular news item.</strong></p>
<p><img title="rss-reader-3-action-share" src="/wp-content/uploads/2012/12/rss-reader-3-action-share.png" alt="" /></p>
<p><strong>step 1</strong>: So create the required menu and when creating the item to set it to default share action as shown in the figure above, we need to add an extra attribute: android:actionProviderClass=&#8221;android.widget.ShareActionProvider&#8221;</p>
<p>Here&#8217;s the &#8216;activity_desc.xml&#8217; created in the menu folder (res/menu):</p><pre class="crayon-plain-tag">&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt;
&lt;item
android:id="@+id/share_option"
android:actionProviderClass="android.widget.ShareActionProvider"
android:showAsAction="ifRoom"
android:title="Share"/&gt;
&lt;/menu&gt;</pre><p><strong>step 2</strong>: And in the description Activity add this implementation to the onCreateOptionsMenu():</p><pre class="crayon-plain-tag">@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_desc, menu);

// Locate MenuItem with ShareActionProvider
MenuItem shareItem = menu.findItem(R.id.share_option);

// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) shareItem
.getActionProvider();

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "RSS Reader");
String shareBody = feed.getItem(pos).getTitle() + "\n"
+ feed.getItem(pos).getDescription();
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);

// Set the share intent
mShareActionProvider.setShareIntent(shareIntent);

return true;
}</pre><p><span class="highlight-red">Note</span>: Please note that you cant test the share functionality in the emulator so find a device running API 14+.</p>
<p>here a bug reported on the same: <a title="http://code.google.com/p/android/issues/detail?id=25467" href="http://code.google.com/p/android/issues/detail?id=25467" target="_blank">http://code.google.com/p/android/issues/detail?id=25467</a></p>
<p>In the above code we just got the action provider which we set from the xml and then we are setting the &#8216;ShareActionProvider&#8217; with an intent having information to share like news title and description. (you can also parse for the link from the RSS to make the share more informational).</p>
<p>With this, the tutorial came to an end and in the next we will see how to make that long list containing on average of 100+ items to load in small chunks where we show a loader at the end of list while it gets the next items.</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" alt="" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a title="https://techiedreams.com/downloads/TD%20Simple%20RSS%20Reader-3.zip" href="/downloads/TD%20Simple%20RSS%20Reader-3.zip"><strong>TD Simple RSS Reader</strong></a></p>
<p><em><strong>Subscribe like and stay tuned!</strong></em></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="1" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li><li data-position="2" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="3" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="4" data-poid="in-700" data-post-type="none" ><a href="/android-flickr-search-with-pagination/" class="wp_rp_title">Android Flickr Search with pagination.</a></li><li data-position="5" data-poid="in-125" data-post-type="none" ><a href="/getting-started-with-android-app-development/" class="wp_rp_title">Getting started with Android Application Development.</a></li></ul></div></div>
<p>The post <a href="/android-rss-reader-part-3-action-bar-with-animated-item/">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-rss-reader-part-3-action-bar-with-animated-item/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</title>
		<link>https://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/</link>
		<comments>https://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 18:47:34 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[RSS Reader]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=424</guid>
		<description><![CDATA[<p>This post is in continuation with the previous Post (Android Simple RSS Reader with Splash Screen and Custom List View.), where we learnt to parse an xml and show that in a ListView followed by a Detail View. In this tutorial we will add some features like &#8216;offline reading&#8217; and &#8216;swipe through detail views&#8217;. Here&#8217;s &#8230;<br/><a class="more-link" href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><em>This post is in continuation with the previous Post (</em><a title="Android Simple RSS Reader with Splash Screen and Custom List View." href="/android-simple-rss-reader/" rel="bookmark">Android Simple RSS Reader with Splash Screen and Custom List View.</a><em>), where we learnt to parse an xml and show that in a ListView followed by a Detail View.</em></p>
<p>In this tutorial we will add some features like &#8216;offline reading&#8217; and &#8216;swipe through detail views&#8217;.</p>
<p><span style="text-decoration: underline;">Here&#8217;s the final video demo:</span></p>
<p><iframe width="610" height="350" src="http://www.youtube.com/embed/4r7MY4Qrdfk" frameborder="0"></iframe></p>
<p><span style="text-decoration: underline;"><strong>First lets get in to the  creation of swipe detail view:</strong></span></p>
<p>Using swipe views we can navigate to other details just by swiping (left and right) unlike going back to list and selecting the item.</p>
<p>To achieve this we use &#8216;<a title="http://developer.android.com/reference/android/support/v4/view/ViewPager.html" href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html" target="_blank">ViewPager</a>&#8216;:</p>
<p>&#8216;ViewPager&#8217; takes in a adapter where we set all the views (In this example we set the fragment as the view).</p>
<p>So we create a detail fragment where it holds all the detail information. From the Adapter we set this fragment each time the user swipes to and fro.</p>
<p>We create a separate layout for this fragment so the Main detail layout (<span style="text-decoration: underline;">detail.xml</span>) will look like this:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="5dp"
android:paddingRight="5dp" &gt;

&lt;android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" &gt;
&lt;/android.support.v4.view.ViewPager&gt;

&lt;/RelativeLayout&gt;</pre><p>Here&#8217;s the details fragment layout (<span style="text-decoration: underline;">detail_fragment.xml</span>):</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="5dp"
android:paddingRight="5dp" &gt;

&lt;TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/title"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" /&gt;

&lt;ScrollView
android:id="@+id/sv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/title"
android:layout_marginTop="10dp" &gt;

&lt;RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" &gt;

&lt;WebView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:scrollbarStyle="insideOverlay"
android:text="@string/desc" /&gt;
&lt;/RelativeLayout&gt;
&lt;/ScrollView&gt;

&lt;/RelativeLayout&gt;</pre><p>The main detail activity extends &#8216;FragmentActivity&#8217;. Here we have a sub class &#8216;DescAdapter&#8217; which extends &#8216;FragmentStatePagerAdapter&#8217;. we can also extend &#8216;FragmentPagerAdapter&#8217; instead, but the difference is that &#8216;FragmentStatePagerAdapter&#8217; will destroy the views once the are out of the window.</p>
<p>Here&#8217;s the final detail Activity (<span style="text-decoration: underline;">DetailActivity.java</span>):</p><pre class="crayon-plain-tag">public class DetailActivity extends FragmentActivity {

RSSFeed feed;
int pos;
private DescAdapter adapter;
private ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);

// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
pos = getIntent().getExtras().getInt("pos");

// Initialize the views
adapter = new DescAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);

// Set Adapter to pager:
pager.setAdapter(adapter);
pager.setCurrentItem(pos);

}

public class DescAdapter extends FragmentStatePagerAdapter {
public DescAdapter(FragmentManager fm) {
super(fm);
}

@Override
public int getCount() {
return feed.getItemCount();
}

@Override
public Fragment getItem(int position) {

DetailFragment frag = new DetailFragment();

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
bundle.putInt("pos", position);
frag.setArguments(bundle);

return frag;
}
}
}</pre><p>In the detail activity adapter, we pass the feed bundle and the position of the item to the detail fragment. In the detail fragment activity which extends a fragment, we receive the bundle and the position and set all the views in the fragment layout.</p>
<p>The detail fragment activity (<span style="text-decoration: underline;">DetailFragment.java</span>) will look like this:</p><pre class="crayon-plain-tag">public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

fFeed = (RSSFeed) getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.detail_fragment, container, false);

// Initializr views
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);

// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);

// Set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setLightTouchEnabled(false);
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);

// Set the views
title.setText(fFeed.getItem(fPos).getTitle());
desc.loadDataWithBaseURL("http://www.androidcentral.com/", fFeed
.getItem(fPos).getDescription(), "text/html", "UTF-8", null);

return view;
}
}</pre><p>With this we have created the horizontal swipe detail views. Run the app to test! (Any issues please use comments, i would be pleased to help you).</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>Now will move on to create the offline support. Achieving this is very simple we just need to save the feed object which we get each time we launch the App.</p>
<p><span style="text-decoration: underline;"><em>Steps involved in this are:</em></span><br />
1. Check for the internet connectivity.<br />
2. If Internet is available then allow to parse, once you get the final feed write that to the file.<br />
3. If connection is not available then first check if the feed file exists if exists then read the feed from the file and proceed.</p>
<p>4. Else if the feed file doesn&#8217;t exist (for the first launch), then show an alert to check for connectivity with only option to exit.</p>
<p><em>We write the feed to the Applications default files directory so that it can&#8217;t be accessed by other apps and deleted when the app is uninstalled.</em></p>
<p>The final &#8216;<span style="text-decoration: underline;">SplashActivity.java</span>&#8216; will looks like this:</p><pre class="crayon-plain-tag">public class SplashActivity extends Activity {

private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;
String fileName;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.splash);

fileName = "TDRSSFeed.td";

File feedFile = getBaseContext().getFileStreamPath(fileName);

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {

// No connectivity. Check if feed File exists
if (!feedFile.exists()) {

// No connectivity &amp; Feed file doesn't exist: Show alert to exit
// &amp; check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});

AlertDialog alert = builder.create();
alert.show();
} else {

// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}

} else {

// Connected - Start parsing
new AsyncLoadXMLFeed().execute();

}
}

private void startLisActivity(RSSFeed feed) {

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);

// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);

// kill this activity
finish();
}

private class AsyncLoadXMLFeed extends AsyncTask&lt;Void, Void, Void&gt; {

@Override
protected Void doInBackground(Void... params) {

// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null &amp;&amp; feed.getItemCount() &gt; 0)
WriteFeed(feed);
return null;

}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

startLisActivity(feed);
}
}

// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {

FileOutputStream fOut = null;
ObjectOutputStream osw = null;

try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}

catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {

FileInputStream fIn = null;
ObjectInputStream isr = null;

RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;

try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);

_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}</pre><p>Last but no least add the required permissions to the Manifest:</p><pre class="crayon-plain-tag">&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
&lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt;</pre><p>Done! Run the App and test in all cases (with connectivity, without connectivity, first time launch with out connectivity). If any problems Please use comments also refer to the sources attached.</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" alt="" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a href="/downloads/TD%20Simple%20RSS%20Reader-3.zip"><strong>TD Simple RSS Reader</strong></a></p>
<p><em>In the next tutorial we will introduce the &#8216;Action Bar&#8217; with some features like refresh, share &#8230;   Stay tuned!</em></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li><li data-position="1" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="2" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="3" data-poid="in-240" data-post-type="none" ><a href="/android-layouts-explained-with-examples/" class="wp_rp_title">Android Layouts explained with examples.</a></li><li data-position="4" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="5" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li></ul></div></div>
<p>The post <a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Android Simple RSS Reader with Splash Screen and Custom List View.</title>
		<link>https://techiedreams.com/android-simple-rss-reader/</link>
		<comments>https://techiedreams.com/android-simple-rss-reader/#comments</comments>
		<pubDate>Thu, 22 Nov 2012 17:42:26 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[RSS Reader]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=371</guid>
		<description><![CDATA[<p>RSS (Reach Site Summary): RSS is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format. &#8211; wikipedia Basically RSS are xml files. We can read RSS files using applications called RSS Readers. In this tutorial we will create a &#8216;Simple RSS &#8230;<br/><a class="more-link" href="/android-simple-rss-reader/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-simple-rss-reader/">Android Simple RSS Reader with Splash Screen and Custom List View.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>RSS (Reach Site Summary)</strong></span>:</p>
<p>RSS is a family of <a title="Web feed" href="http://en.wikipedia.org/wiki/Web_feed">web feed</a> formats used to publish frequently updated works—such as <a title="Blog" href="http://en.wikipedia.org/wiki/Blog">blog</a> entries, news headlines, audio, and video—in a standardized format. &#8211; <em><a title="http://en.wikipedia.org/wiki/RSS" href="http://en.wikipedia.org/wiki/RSS">wikipedia</a></em></p>
<p>Basically RSS are xml files. We can read RSS files using applications called RSS Readers. In this tutorial we will create a &#8216;Simple RSS Reader&#8217; app with some basic functionalities like:</p>
<p>1. A splash screen with a spinner and background image shown while the data XML being parsed.</p>
<p>2. From the feed returned by the Parser displaying the thumbnail image, title &amp; date in a <a title="https://techiedreams.com/android-simple-custom-list-views-with-examples/" href="/android-simple-custom-list-views-with-examples/" target="_blank">custom List View</a>.</p>
<p>2. On click of the list item, the description shown in a separate Activity.</p>
<p><span style="text-decoration: underline;">Here&#8217;s the final demo of the &#8216;Simple RSS Reader&#8217; App on a emulator</span>:</p>
<p><iframe width="610" height="360" src="http://www.youtube.com/embed/aJGxQb5B_r8?wmode=transparent" frameborder="0"></iframe></p>
<p><span style="text-decoration: underline;">Analyzing the XML</span>:</p>
<p>In this tutorial is used an external &#8216;xml&#8217; (RSS) of the website [<a title="http://www.androidcentral.com" href="http://www.androidcentral.com" target="_blank">http://www.androidcentral.com</a>]</p>
<p>RSS Link:<del> <a title="http://www.mobilenations.com/rss/mb.xml" href="http://www.mobilenations.com/rss/mb.xml" target="_blank">http://www.mobilenations.com/rss/mb.xml</a></del></p>
<p><strong>NOTE</strong>: Currently the above URL is not working, so for the demo code downloadable i have uploaded the source with a different URL: <a href="http://feeds.feedburner.com/androidcentral?format=xml" target="_blank">http://feeds.feedburner.com/androidcentral?format=xml</a></p>
<p>You can see the structure of the XML(tags) used in it by going to the code view of the link. Here is the example &#8216;item&#8217; &lt;tag&gt; used in the XML:</p><pre class="crayon-plain-tag">&lt;item&gt;

&lt;title&gt;Voice Controlled: A guide to using speech with Windows Phone 8&lt;/title&gt;

&lt;description&gt;
&lt;div id="comment-wrapper-nid-13725" &gt;&lt;/div&gt;
&lt;div&gt;&lt;div&gt;&lt;div&gt;
&lt;p style="" &gt;
&lt;img
alt="Getting chatty with Windows Phone 8"
height="365"
src="http://cdn.wpcentral.com/sites/wpcentral.com/files/styles/large/public/field/image/2012/11/HandHolding_Speech_ws.jpg"
width="650" /&gt;
&lt;/p&gt;
&lt;p
Speech has always been a part of Windows Phone and it has offered some nice ways of interacting with your handset by using your voice alone.
&lt;/p&gt;
&lt;p&gt;
We have put together a guide that should suit those that are new to Windows Phone and also to those that have upgraded to
&lt;a href="http://www.wpcentral.com/windows-phone-8" &gt;
Windows Phone 8 &lt;/a&gt;. Interacting with voice recognition and commands can be a powerful and time saving way to use your phone efficiently and even safely.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div&gt;&lt;div&gt;Tag: &lt;/div&gt;&lt;div&gt;&lt;div&gt;
&lt;a href="/tag/windowsphone8" &gt;
windowsphone8
&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/speech" &gt;speech&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/how" &gt;how-to&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/text-speech" &gt;Text to Speech&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/text-voice" &gt;text to voice&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/wp8" &gt;WP8&lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href="/tags/wp7" &gt;wp7&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;div&gt;&lt;div&gt;
&lt;a href="/category/how" &gt;How To&lt;/a&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;
&lt;/description&gt;

&lt;link&gt;http://www.wpcentral.com/voice-controlled-guide-using-speech-windows-phone-8&lt;/link&gt;

&lt;pubDate&gt;Thu, 22 Nov 2012 14:12:52 +0000&lt;/pubDate&gt;

&lt;guid isPermaLink="&lt;a&gt;false&lt;/a&gt;"&gt;13725 at http://www.wpcentral.com&lt;/guid&gt;
&lt;dc:creator&gt;robert brand&lt;/dc:creator&gt;

&lt;/item&gt;</pre><p>Here from the above &lt;item&gt; we need to get some of the elements for our app, like we need a title(&lt;title&gt;&lt;/title&gt;) description(&lt;description&gt;&lt;/description&gt;) publication date(&lt;pubDate&gt;&lt;/pubDate&gt;) and finally a thumbnail image.</p>
<p>But as you can see in the item we dint find a image tag or any tag related to the image, but if you observe the description we have a image link inside it with in HTML tags. So to get he image link we need to parse the HTML description for &#8216;&lt;img src=&#8221; image link&#8221;&gt;&#8217; .</p>
<p>So here we have to perform html parsing over the description which we will get after parsing the XML. So we need an HTML Parser, we use an external library called &#8216;jsoup&#8217; to perform this html parsing. The library can be downloaded at: <a title="http://jsoup.org/download" href="http://jsoup.org/download" target="_blank">http://jsoup.org/download</a>. Add the library to the project.</p>
<p>Also i used some external classes from: <a title="https://github.com/thest1/LazyList" href="https://github.com/thest1/LazyList" target="_blank">https://github.com/thest1/LazyList</a> to Lazily load the images in the ListView. Here are the list of classes i used :</p>
<ul style="list-style-type: circle;">
<li>FileCache.java</li>
<li>ImageLoader.java</li>
<li>MemoryCache.java</li>
<li>Utils.java</li>
</ul>
<p><span style="text-decoration: underline;">Now lets get started with building process step by step:</span></p>
<p><strong>step 1</strong>: Create a New Project (&#8216;Simple RSS Reader&#8217;) with some package name &amp; a default blank Activity.</p>
<p><span style="text-decoration: underline;">Creating a Splash Screen</span>:</p>
<p><strong>step 2</strong> : As you seen in the video demo a splash screen is shown on launch of the app where all the parsing of the data from the XML is done. So first lets create a Splash Screen Activity: SplashActivity.java(You can rename the blank activity created).</p>
<p>Next we need to create a layout for the Activity. Use a Relative layout to show an image and a loading spinner with some text below it. The final Layout file will look like this:</p>
<p><span style="text-decoration: underline;">splash.xml</span>:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" &gt;

&lt;ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/app_name"
android:src="@drawable/mwm_small" /&gt;

&lt;LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:orientation="horizontal" &gt;

&lt;ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /&gt;

&lt;TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:text="@string/loading" /&gt;
&lt;/LinearLayout&gt;

&lt;/RelativeLayout&gt;</pre><p>In the SplashActivity.java set the content view to the layout created: setContentView(R.layout.splash);</p>
<p><strong>step 3</strong>: Now before starting the parsing process we need to check for the Internet connectivity. If we are connected then we can proceed with the parsing else we will show an alert to check for connectivity. The following code shows how to check for connectivity and displaying a Dialog if there&#8217;s no connectivity:</p><pre class="crayon-plain-tag">ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&amp;&amp; !conMgr.getActiveNetworkInfo().isConnected()
&amp;&amp; !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});

AlertDialog alert = builder.create();
alert.show();

} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}</pre><p>Here&#8217;s the result of the above layout:<br />
<img class="size-full wp-image-416 aligncenter" title="Simple RSS Reader - Splash" src="/wp-content/uploads/2012/11/Simple-RSS-Reader-Splash.png" alt="" width="200" height="333" /></p>
<p><span style="text-decoration: underline;">Parsing the XML</span>:</p>
<p><strong>step 4</strong>: We need to perform the parsing in a separate thread, we achieve that by using the &#8216;AsyncTask&#8217; Class. The reason to perform the parsing in a separate thread is if you start the parsing in the main thread or the UI thread then the application may clog as the Parsing is a potentially a time taking process.</p>
<p>So we create a sub class called &#8216;AsyncLoadXMLFeed&#8217; which extends AsyncTack. In the class we implement the methods: doInBackground() and onPostExecute(). In doInBackground() method we start the Parsing process and once if the Parsing has done then it triggers the onPostExecute() method where we can perform action that has to be done after Parsing(starting the List Activity).</p>
<p><span style="text-decoration: underline;">DOM Parser</span>:</p>
<p><strong>step 5</strong>: Before jumping in to the parsing we create two classes called: &#8216;RSSItem&#8217; and &#8216;RSSFeed&#8217; both implements Serializable.</p>
<p>RSSItem: This class contains the String variables which holds the required data from each item in the XML. We have also some setters and getters to set and get the item data. Here the final RSSItem class:</p>
<p>&#8216;<span style="text-decoration: underline;">RSSItem.java</span>&#8216;:</p><pre class="crayon-plain-tag">public class RSSItem implements Serializable {

private static final long serialVersionUID = 1L;
private String _title = null;
private String _description = null;
private String _date = null;
private String _image = null;

void setTitle(String title) {
_title = title;
}

void setDescription(String description) {
_description = description;
}

void setDate(String pubdate) {
_date = pubdate;
}

void setImage(String image) {
_image = image;
}

public String getTitle() {
return _title;
}

public String getDescription() {
return _description;
}

public String getDate() {
return _date;
}

public String getImage() {
return _image;
}

}</pre><p>RSSFeed: This class object holds all the Items (RSSItem&#8217;s) that have been parsed. It contains a List where we add the RSSItems by a method called addItem(RSSItem item):</p><pre class="crayon-plain-tag">List&lt;RSSItem&gt; _itemlist;

void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}</pre><p>We have also a method called getItemCount() to get the total number of items in the feed.</p>
<p>The final RSSFeed class is here:</p>
<p>&#8216;<span style="text-decoration: underline;">RSSFeed.java</span>&#8216;</p><pre class="crayon-plain-tag">public class RSSFeed implements Serializable {

private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;

RSSFeed() {
_itemlist = new Vector(0);
}

void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}

public RSSItem getItem(int location) {
return _itemlist.get(location);
}

public int getItemCount() {
return _itemcount;
}

}</pre><p><strong>step 6</strong>: Now we need to create a Parser class where it takes the url and performs the Parsing. We write some conditions to check for the tags and we set the RSSItems and finally the RSSFeed.</p>
<p>In this example we use DOM Parser to Parse the XML data. We create a class called &#8216;DOMParser&#8217; in which we create a method of type RSSFeed called parseXML(String xml) which takes in a url as parameter. Once the Parsing is done the method returns the feed(RSSFeed) object:</p><pre class="crayon-plain-tag">private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// Parser the XML and Return the RSSFeed Object(_feed).
return _feed;
}</pre><p>Here is the final &#8216;<span style="text-decoration: underline;">DOMParser.java</span>&#8216; :</p><pre class="crayon-plain-tag">public class DOM_Parser {

private RSSFeed _feed = new RSSFeed();

public RSSFeed parseXml(String xml) {

URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

// Get all tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();

for (int i = 0; i &lt; length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();

NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();

// Get the required elements from each Item
for (int j = 0; j &lt; clength; j++) {

Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();

theString = nchild.item(j).getFirstChild().getNodeValue();

if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}

else if ("description".equals(nodeName)) {
_item.setDescription(theString);

// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}

else if ("pubDate".equals(nodeName)) {

// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}

}
}

// add item to the list
_feed.addItem(_item);
}

} catch (Exception e) {
}

// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}

}</pre><p><strong>step 7</strong>: Now we have our Parser ready. In the Splash Activity we now call the method parseXml(String xml) from the DOMParser class with the URL we got(http://www.mobilenations.com/rss/mb.xml) as the parameter:</p><pre class="crayon-plain-tag">DOMParser myParser = new DOMParser();
feed = myParser.parseXml("http://www.mobilenations.com/rss/mb.xml");</pre><p>Once after the feed has been obtained in the onPostExecute() method we need to start the ListActivity and pass it the feed we got, we do that by bundling the feed object and attaching it to the Intent:</p><pre class="crayon-plain-tag">Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);

// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);</pre><p><strong>step 8</strong>: The final &#8216;<span style="text-decoration: underline;">SplashActivity.java</span>&#8216; will looks as follows:</p><pre class="crayon-plain-tag">public class SplashActivity extends Activity {

private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.splash);

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&amp;&amp; !conMgr.getActiveNetworkInfo().isConnected()
&amp;&amp; !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});

AlertDialog alert = builder.create();
alert.show();

} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();

}

}

private class AsyncLoadXMLFeed extends AsyncTask {

@Override
protected Void doInBackground(Void... params) {

// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
return null;

}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);

// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);

// kill this activity
finish();
}
}
}</pre><p><span style="text-decoration: underline;">Custom List Activity</span>:</p>
<p><strong>step 9</strong>: To display the feed items in a list we need to create a custom List View with each List item containing a title, a thumbnail image &amp; a date. Creating a custom list view has been posted in the previous tutorial titled: <a title="Android simple &amp; custom List views with examples." href="/android-simple-custom-list-views-with-examples/" rel="bookmark">Android simple &amp; custom List views with examples.</a></p>
<p>Please refer the above mentioned post to understand how to create a custom list view.</p>
<p>A screen shot of the Custom List that we are going to achieve is shown below:</p>
<p><img class="size-full wp-image-409 aligncenter" title="Simple RSS Reader - List" src="/wp-content/uploads/2012/11/Simple-RSS-Reader-List.png" alt="" width="211" height="330" /></p>
<p>Here are the files i used to create the above Custom List View:</p>
<p>Layout files:</p>
<p>&#8216;<span style="text-decoration: underline;">feed_list.xml</span>&#8216;:</p><pre class="crayon-plain-tag">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" &gt;

&lt;ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" &gt;
&lt;/ListView&gt;

&lt;/LinearLayout&gt;</pre><p>&#8216;<span style="text-decoration: underline;">list_item.xml</span>&#8216;:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="2dp" &gt;

&lt;ImageView
android:id="@+id/thumb"
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name" /&gt;

&lt;RelativeLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/arrow"
android:layout_toRightOf="@+id/thumb"
android:orientation="vertical" &gt;

&lt;TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="@string/title"
android:textSize="16dp"
android:textStyle="bold" /&gt;

&lt;TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="@string/date"
android:textColor="#7F7F7F"
android:textSize="10dp" /&gt;
&lt;/RelativeLayout&gt;

&lt;ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:contentDescription="@string/app_name"
android:src="@drawable/arrow_next" /&gt;

&lt;/RelativeLayout&gt;</pre><p>&#8216;<span style="text-decoration: underline;">ListActivity.java</span>&#8216;:</p><pre class="crayon-plain-tag">public class ListActivity extends Activity {

Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.feed_list);

myApp = getApplication();

// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");

// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
lv.setVerticalFadingEdgeEnabled(true);

// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
lv.setAdapter(adapter);

// Set on item click listener to the ListView
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);

}
});

}

@Override
protected void onDestroy() {
super.onDestroy();
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}

class CustomListAdapter extends BaseAdapter {

private LayoutInflater layoutInflater;
public ImageLoader imageLoader;

public CustomListAdapter(ListActivity activity) {

layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}

@Override
public int getCount() {

// Set the total list item count
return feed.getItemCount();
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item, null);
}

// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvDate = (TextView) listItem.findViewById(R.id.date);

// Set the views in the layout
imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvDate.setText(feed.getItem(pos).getDate());

return listItem;
}
}
}</pre><p>In the above List Activity in the Adapter class to set the thumbnail image we used the &#8216;ImageLoader&#8217; Class which we copied to Project earlier along with some other supporting classes.</p>
<p>And in the onItemClickListner(), we are Passing the feed along with the position of the item clicked to the &#8216;DetailActivity&#8217;.</p>
<p><strong>step 10</strong>: So lets now create the &#8216;DetailActivity&#8217; which takes in the feed and position to display the title and the full description in a WebView.</p>
<p>The Layout used in detail Activity should contain a TextView to hold the title and a WebView to hold the description. (As the description we got from the parser is a HTML text we need the WebView to display the description instead of a TextView.)</p>
<p>The final &#8216;<span style="text-decoration: underline;">detail.xml</span>&#8216; will looks like this:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="2dp" &gt;

&lt;ImageView
android:id="@+id/thumb"
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name" /&gt;

&lt;RelativeLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/arrow"
android:layout_toRightOf="@+id/thumb"
android:orientation="vertical" &gt;

&lt;TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="@string/title"
android:textSize="16dp"
android:textStyle="bold" /&gt;

&lt;TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="@string/date"
android:textColor="#7F7F7F"
android:textSize="10dp" /&gt;
&lt;/RelativeLayout&gt;

&lt;ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:contentDescription="@string/app_name"
android:src="@drawable/arrow_next" /&gt;

&lt;/RelativeLayout&gt;</pre><p>Here&#8217;s the result of the above layout:<br />
<img class="size-full wp-image-417 aligncenter" title="Simple RSS Reader - Detail" src="/wp-content/uploads/2012/11/Simple-RSS-Reader-Detail.png" alt="" width="213" height="330" /></p>
<p>In the &#8216;DetailActivity&#8217; we created, we need to get the feed and the position that has been passed from the List Activiy. We can get the Intent data by using getIntent() method:</p><pre class="crayon-plain-tag">RSSFeed feed = (RSSFeed) getIntent().getExtras().get("feed");
int pos = getIntent().getExtras().getInt("pos");</pre><p>And once we got the feed and the Position we can set the views in the Layout. The final &#8216;DetailActivity&#8217; will looks like this:</p><pre class="crayon-plain-tag">public class DetailActivity extends Activity {

RSSFeed feed;
TextView title;
WebView desc;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);

// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);

// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
int pos = getIntent().getExtras().getInt("pos");

// Initialize the views
title = (TextView) findViewById(R.id.title);
desc = (WebView) findViewById(R.id.desc);

// set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.getPluginState();
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
ws.setBuiltInZoomControls(true);

// Set the views
title.setText(feed.getItem(pos).getTitle());
desc.loadDataWithBaseURL("http://www.androidcentral.com/", feed
.getItem(pos).getDescription(), "text/html", "UTF-8", null);
}

}</pre><p><strong>step 11</strong>: Do not forget to register the Activities in the Manifest and also set the required permissions:</p>
<p>The final Manifest will look like this:</p><pre class="crayon-plain-tag">&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.td.rssreader"
android:versionCode="1"
android:versionName="1.0" &gt;

&lt;uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" /&gt;

&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;

&lt;application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" &gt;
&lt;activity
android:name=".SplashActivity"
android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" &gt;
&lt;intent-filter&gt;
&lt;action android:name="android.intent.action.MAIN" /&gt;

&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;activity android:name=".ListActivity" /&gt;
&lt;activity android:name=".DetailActivity" /&gt;
&lt;/application&gt;

&lt;/manifest&gt;</pre><p>We are done now! Run the Application!</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" alt="" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a title="https://techiedreams.com/downloads/TD%20Simple%20RSS%20Reader.zip" href="/downloads/TD%20Simple%20RSS%20Reader-3.zip"><strong>TD Simple RSS Reader</strong></a></p>
<p>In up coming tutorials we talk about bringing this &#8216;Simple RSS Reader&#8217; to a beautiful RSS Reader Application by adding the features like: Offline Reading, pull to refresh List, Swipe through the Details,  Action Bar,  Font size increase and decrease in the description view and more other miscellaneous features.</p>
<p><strong>* Playing Youtube videos:</strong></p>
<p>One way is to install flash on the device or the emulator on which you are installing the App.</p>
<p>The other way is to use the external library which takes care of playing the video. I would suggest this library <a title="http://code.google.com/p/android-youtube-player/downloads/list" href="http://code.google.com/p/android-youtube-player/downloads/list" target="_blank">http://code.google.com/p/android-youtube-player/downloads/list</a></p>
<p>Download the jar add it your Project.</p>
<p>In the description class where you want to play the video add a button image overlay over the webview or the ImageView and onClick of the button start the Video Intent:</p><pre class="crayon-plain-tag">String url = feed.getItem(position).getLink();
String Vid = null;
Pattern pattern = Pattern.compile("embed/(.*?)\\?");
Matcher matcher = pattern.matcher(url);
if (matcher.find())
Vid = matcher.group(1);
if (Vid != null) {
Intent videoIntent = new Intent(null, Uri.parse("ytv://" + Vid),
GM_Video_Desc.this, OpenYouTubePlayerActivity.class);
startActivity(videoIntent);
}</pre><p>Also do not forget to register the activity and to add the required permissions  in Manifest:</p><pre class="crayon-plain-tag">uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_WIFI_STATE"

&lt;activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"
android:screenOrientation="landscape" /&gt;</pre><p></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="1" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="2" data-poid="in-240" data-post-type="none" ><a href="/android-layouts-explained-with-examples/" class="wp_rp_title">Android Layouts explained with examples.</a></li><li data-position="3" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="4" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="5" data-poid="in-125" data-post-type="none" ><a href="/getting-started-with-android-app-development/" class="wp_rp_title">Getting started with Android Application Development.</a></li></ul></div></div>
<p>The post <a href="/android-simple-rss-reader/">Android Simple RSS Reader with Splash Screen and Custom List View.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-simple-rss-reader/feed/</wfw:commentRss>
		<slash:comments>164</slash:comments>
		</item>
		<item>
		<title>Android custom Grid View with zoom-in animation effect.</title>
		<link>https://techiedreams.com/android-custom-grid-view-with-zoom-in-animation-effect/</link>
		<comments>https://techiedreams.com/android-custom-grid-view-with-zoom-in-animation-effect/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 12:15:22 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Grid View]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=342</guid>
		<description><![CDATA[<p>Android Grid View: In a Grid View all the views are arranged in the grid fashion. We can customize a Grid View by creating a custom layout for the contents of the grid item. Here in this example we create a Grid View with the grids containing a simple layout have an Image View that &#8230;<br/><a class="more-link" href="/android-custom-grid-view-with-zoom-in-animation-effect/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-custom-grid-view-with-zoom-in-animation-effect/">Android custom Grid View with zoom-in animation effect.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>Android Grid View: </strong></p>
<p>In a Grid View all the views are arranged in the grid fashion. We can customize a Grid View by creating a custom layout for the contents of the grid item.</p>
<p>Here in this example we create a Grid View with the grids containing a simple layout have an Image View that holds a thumbnail.</p>
<p>We have different cases where we need to display those thumbs are the grid views in a separate layout with larger images. We can achieve this by starting a new Activity on a grid item click with the image reference and showing it in that activity.</p>
<p>But here in the example on a grid item (thumbnail) click, we zoom-in form the thumbnail to full screen image with a growing animation effect.</p>
<p><span style="text-decoration: underline;">Here&#8217;s the Demo of the final Project:</span></p>
<p><iframe width="615" height="360" src="http://www.youtube.com/embed/sPRR7Xj1hfc?wmode=transparent" frameborder="2"></iframe></p>
<p>Here are the steps in creating the project:</p>
<p><strong>step 1:</strong> Create a New Android Project with a blank activity(MainActivity.java) and a layout(activity_main.xml).</p>
<p><strong>step 2:</strong> To the main layout(activity_main.xml) Add a Frame Layout as the root and then a Grid View followed by an Image View &#8211; to display the zoomed-in image of the thumbnail:</p>
<p>Note: We use frame layout because we are initially hiding the full screen ImageView and showing it on click on the Grid Item. As all the Views in a frame layout are stacked one on other we can display a View over another View.</p>
<p>For more info on Frame Layouts refer: <a title="http://developer.android.com/reference/android/widget/FrameLayout.html" href="http://developer.android.com/reference/android/widget/FrameLayout.html" target="_blank">http://developer.android.com/reference/android/widget/FrameLayout.html</a></p>
<p><span style="text-decoration: underline;">activity_main.xml:</span></p><pre class="crayon-plain-tag">&lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" &gt;

&lt;GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="80dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" &gt;
&lt;/GridView&gt;

&lt;ImageView
android:id="@+id/expanded_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@string/app_name"
android:visibility="invisible" /&gt;

&lt;/FrameLayout&gt;</pre><p>step 3: Create a new layout for the Grid Item (grid_item.xml) with an Image View to hold the thumbnail:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" &gt;

&lt;ImageView
android:id="@+id/thumb"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_centerHorizontal="true"
android:contentDescription="@string/app_name" /&gt;

&lt;/RelativeLayout&gt;</pre><p>step 4:<br />
The final main Activity(MainActivity.java) looks as follows (Commented wherever necessary for better understanding the flow) :</p><pre class="crayon-plain-tag">public class MainActivity extends Activity {

// Declare variables / references
private GridView gv;
private Animator mCurrentAnimator;
private int mShortAnimationDuration;

// Create Array thumbs resource id's:
private int thumb[] = { R.drawable.cupcake, R.drawable.donut,
R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread,
R.drawable.honeycomb, R.drawable.icecreamsandwich,
R.drawable.jellybean, R.drawable.cupcake, R.drawable.donut,
R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread,
R.drawable.honeycomb, R.drawable.icecreamsandwich,
R.drawable.jellybean };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize the variables:
gv = (GridView) findViewById(R.id.gridView);

// Set an Adapter to the ListView
gv.setAdapter(new ImageAdapter(this));

// Set on item click listener to the ListView
gv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView&lt;?&gt; parent, View v, int pos,
long id) {

// Display the zoomed in image in full screen
zoomImageFromThumb(v, thumb[pos]);

}
});

// Set the Animation time form the android defaults
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);

}

// Create an Adapter Class extending the BaseAdapter
class ImageAdapter extends BaseAdapter {

private LayoutInflater layoutInflater;

public ImageAdapter(MainActivity activity) {
// TODO Auto-generated constructor stub
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// Set the count value to the total number of items in the Array
return thumb.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.grid_item, null);
}

// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);

// Set the views in the layout
iv.setBackgroundResource(thumb[pos]);

return listItem;
}

}

private void zoomImageFromThumb(final View thumbView, int imageResId) {
// If there's an animation in progress, cancel it immediately and
// proceed with this one.
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

// Load the high-resolution "zoomed-in" image.
final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
expandedImageView.setImageResource(imageResId);

// Calculate the starting and ending bounds for the zoomed-in image.
// This step
// involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();

// The start bounds are the global visible rectangle of the thumbnail,
// and the
// final bounds are the global visible rectangle of the container view.
// Also
// set the container view's offset as the origin for the bounds, since
// that's
// the origin for the positioning animation properties (X, Y).
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds,
globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);

// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the
// "center crop" technique. This prevents undesirable stretching during
// the animation.
// Also calculate the start scaling factor (the end scaling factor is
// always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height() &gt; (float) startBounds
.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}

// Hide the thumbnail and show the zoomed-in view. When the animation
// begins,
// it will position the zoomed-in view in the place of the thumbnail.
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);

// Set the pivot point for SCALE_X and SCALE_Y transformations to the
// top-left corner of
// the zoomed-in view (the default is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);

// Construct and run the parallel animation of the four translation and
// scale properties
// (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set.play(
ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y,
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;

// Upon clicking the zoomed-in image, it should zoom back down to the
// original bounds
// and show the thumbnail instead of the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

// Animate the four positioning/sizing properties in parallel,
// back to their
// original values.
AnimatorSet set = new AnimatorSet();
set.play(
ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
}</pre><p>&nbsp;</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a title="https://techiedreams.com/downloads/TD%20Custom%20Grid%20View%20Animated.zip" href="/downloads/TD%20Custom%20Grid%20View%20Animated.zip"><strong>TD Custom Grid View Animation</strong></a></p>
<p><strong>Credit:</strong> <a title="https://plus.google.com/113735310430199015092/about" href="https://plus.google.com/113735310430199015092/about" target="_blank">Roman Nurik</a></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li><li data-position="1" data-poid="in-240" data-post-type="none" ><a href="/android-layouts-explained-with-examples/" class="wp_rp_title">Android Layouts explained with examples.</a></li><li data-position="2" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="3" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="4" data-poid="in-186" data-post-type="none" ><a href="/activity-and-its-life-cycle/" class="wp_rp_title">Android Activity and its Life Cycle.</a></li><li data-position="5" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li></ul></div></div>
<p>The post <a href="/android-custom-grid-view-with-zoom-in-animation-effect/">Android custom Grid View with zoom-in animation effect.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-custom-grid-view-with-zoom-in-animation-effect/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Android simple &amp; custom List views with examples.</title>
		<link>https://techiedreams.com/android-simple-custom-list-views-with-examples/</link>
		<comments>https://techiedreams.com/android-simple-custom-list-views-with-examples/#comments</comments>
		<pubDate>Sun, 11 Nov 2012 14:25:14 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[List View]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=302</guid>
		<description><![CDATA[<p>Android List View: Android List Views are like any other lists where we have a series of items aligned in a vertical fashion. In Android List Views are used in many ways, most likely as Menu&#8217;s to navigate to different screens. Generally list views are used to show a single or multiple lines of text &#8230;<br/><a class="more-link" href="/android-simple-custom-list-views-with-examples/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-simple-custom-list-views-with-examples/">Android simple &#038; custom List views with examples.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>Android List View:</strong></p>
<p>Android List Views are like any other lists where we have a series of items aligned in a vertical fashion. In Android List Views are used in many ways, most likely as Menu&#8217;s to navigate to different screens. Generally list views are used to show a single or multiple lines of text as the list items but we can customize the list view to show  a layout ( for ex: containing a thumbnail a Text Heading and and another Text to show the description) as the list item.</p>
<p>Lets start with creating a simple List View:</p>
<p><strong>Simple List View example:</strong></p>
<p>Lets create a Simple List View with a list of strings and showing a &#8216;Toast&#8217; on clicking the particular List item:</p>
<p>The final out put will look like this:</p>
<p><img class="size-full wp-image-305 aligncenter" title="simple-list-screen" alt="" src="/wp-content/uploads/2012/11/simple-list-screen.png" width="250" height="388" /></p>
<p>Hers are the steps to create a Simple List View:</p>
<p>step 1: Create a new Project with a blank Activity(&#8216;MainActivity.java&#8217;).</p>
<p>step 2: Open the main activity class file (&#8216;MainActivity.java&#8217; in my case), You can see that it extends an &#8216;Activity&#8217; but for creating a simple list view we need to extend the &#8216;ListActivity&#8217;, change the code accordingly:</p><pre class="crayon-plain-tag">public class MainActivity extends ListActivity {
.
.
.
}</pre><p>step 3: We need to have a set of strings to feed the list view, so create a string array[] with some name (listItems[] in my case):</p><pre class="crayon-plain-tag">String listItems[] = { "List Item 1", "List Item 2", "List Item 3",
"List Item 4", "List Item 5", "List Item 6", "List Item 7",
"List Item 8", "List Item 9", "List Item 10", "List Item 11",
"List Item 12" };</pre><p>step 4: List View requires an Adapter to feed the list, create an Array adapter with the array we created in the last step:</p><pre class="crayon-plain-tag">ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this,
android.R.layout.simple_list_item_1, listItems);</pre><p>step 6: All set now! we need to set the main view, Generally we set the views from the layout file (setContentView()) but here we don&#8217;t require a Layout so set the List Adapter(setListAdapter(adapter)):</p><pre class="crayon-plain-tag">setListAdapter(adapter);</pre><p>Now Run the application and you can see a list with all the items in the Array. But here nothing happens when you click on the list items. To perform an action on the list item click, we need to set a Listener() to the ListView, As we are extending the ListActivity we can implement the ListActivity methods directly by Rightclicking in the editor &gt; &#8216;Source&#8217; &gt; &#8216;Override/Implement Methods..&#8217;. &gt; Under &#8216;ListActivity&#8217; &gt; Select &#8216;onListItemClickListner()&#8217; &gt; Click &#8216;OK&#8217; :</p><pre class="crayon-plain-tag">@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
//Display a toast on item clicked in the List
Toast toast = Toast.makeText(this, "You clicked on: " + listItems[position], Toast.LENGTH_SHORT);
toast.show();
}</pre><p>onListItemClick() method gives you the position of the list item clicked. With the position got display the &#8216;Toast&#8217; with the respective title from the Array ( listItems[position] ).</p>
<p>The final code will look as follows:</p><pre class="crayon-plain-tag">public class MainActivity extends ListActivity {

//Create an array of list items
private String listItems[] = { "List Item 1", "List Item 2", "List Item 3",
"List Item 4", "List Item 5", "List Item 6", "List Item 7",
"List Item 8", "List Item 9", "List Item 10", "List Item 11",
"List Item 12" };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//Create ArrayAdapter using the array(listItems)
ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this,
android.R.layout.simple_list_item_1, listItems);

//Set the ArrayAdapter as the ListView's adapter
setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);

//Display a toast on item clicked in the List
Toast toast = Toast.makeText(this, "You clicked on: " + listItems[position], Toast.LENGTH_SHORT);
toast.show();
}
}</pre><p>&nbsp;</p>
<p>Done!! Run the App and see the result.</p>
<p><strong>Custom List View: </strong></p>
<p>Lets create a custom List view with list items containing a thumbnail and and some text. The final out put is shown below:</p>
<p><img class="size-full wp-image-315 aligncenter" title="custom-list-screen" alt="" src="/wp-content/uploads/2012/11/custom-list-screen.png" width="250" height="388" /></p>
<p>Here&#8217;s the steps to create the Custom List View:</p>
<p>step 1: Create a new Project with a blank Activity.</p>
<p>step 2: Create the main layout (activity_main.xml) with a list view as shown below:</p><pre class="crayon-plain-tag">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" &gt;

&lt;ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" &gt;
&lt;/ListView&gt;

&lt;/LinearLayout&gt;</pre><p>step 3: Create a layout for the list item (list_item.xml) as shown below:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" &gt;

&lt;ImageView
android:id="@+id/thumb"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="@string/app_name" /&gt;

&lt;LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_toLeftOf="@+id/arrow"
android:layout_toRightOf="@+id/thumb"
android:orientation="vertical" &gt;

&lt;TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title"
android:textSize="16dp"
android:textStyle="bold" /&gt;

&lt;TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/desc"
android:textSize="12dp" /&gt;
&lt;/LinearLayout&gt;

&lt;ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:contentDescription="@string/app_name"
android:src="@drawable/arrow_next" /&gt;

&lt;/RelativeLayout&gt;</pre><p>step 4:</p>
<p>Create a Main Class Activity (MainActivity.java) as shown below:</p><pre class="crayon-plain-tag">public class MainActivity extends Activity {

private ListView lv;

// Create Array's of titles, descriptions and thumbs resource id's:
private String title[] = { "Cup Cake", "Donut", "Eclair", "Froyo",
"Ginger Bread", "Honey Comb", "Icecream Sandwich", "Jelly Bean" };

private String desc[] = { "version: 1.5", "version: 1.6",
"version: 2.0 &amp; 2.1", "version: 2.2", "version: 2.3",
"version: 3.0", "version: 4.0", "version: 4.1" };

private int thumb[] = { R.drawable.cupcake, R.drawable.donut,
R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread,
R.drawable.honeycomb, R.drawable.icecreamsandwich,
R.drawable.jellybean, };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);

// Set an Adapter to the ListView
lv.setAdapter(new VersionAdapter(this));

// Set on item click listener to the ListView
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;

LayoutInflater layoutInflator = getLayoutInflater();

View layout = layoutInflator.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));

ImageView iv = (ImageView) layout.findViewById(R.id.toast_iv);
TextView tv = (TextView) layout.findViewById(R.id.toast_tv);

iv.setBackgroundResource(thumb[pos]);
tv.setText(title[pos]);

Toast toast = new Toast(getApplicationContext());
toast.setView(layout);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});

}

// Create an Adapter Class extending the BaseAdapter
class VersionAdapter extends BaseAdapter {

private LayoutInflater layoutInflater;

public VersionAdapter(MainActivity activity) {
// TODO Auto-generated constructor stub
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// Set the count value to the total number of items in the Array
return title.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item, null);
}

// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvDesc = (TextView) listItem.findViewById(R.id.desc);

// Set the views in the layout
iv.setBackgroundResource(thumb[pos]);
tvTitle.setText(title[pos]);
tvDesc.setText(desc[pos]);

return listItem;
}

}

}</pre><p>step 5: Lets display a &#8216;Custom Toast&#8217; with an image and text on click of the list item:</p>
<p><img class="size-full wp-image-320 aligncenter" title="custom-list-screen2" alt="" src="/wp-content/uploads/2012/11/custom-list-screen2.png" width="250" height="387" /></p>
<p><strong>Creating custom Toast:</strong></p>
<p>It&#8217;s quite simple create a layout with the desired elements to show in the &#8216;Toast&#8217;, in my case a main/root layout an image view and a text view:</p>
<p>custom_toast.xml:</p><pre class="crayon-plain-tag">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#DAAA"
android:orientation="vertical"
android:padding="8dp" &gt;

&lt;ImageView
android:id="@+id/toast_iv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center_horizontal"
android:contentDescription="@string/app_name" /&gt;

&lt;TextView
android:id="@+id/toast_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#FFF" /&gt;

&lt;/LinearLayout&gt;</pre><p>Create a view by inflating the layout and attach that to the Toast by toast.setView(view):</p><pre class="crayon-plain-tag">LayoutInflater layoutInflator = getLayoutInflater();

View layout = layoutInflator.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));

ImageView iv = (ImageView) layout.findViewById(R.id.toast_iv);
TextView tv = (TextView) layout.findViewById(R.id.toast_tv);

iv.setBackgroundResource(thumb[pos]);
tv.setText(title[pos]);

Toast toast = new Toast(getApplicationContext());
toast.setView(layout);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();</pre><p>&nbsp;</p>
<p>Also refer:</p>
<p><a title="http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView" href="http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView" target="_blank">http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView</a></p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a title="https://techiedreams.com/downloads/TD Simple List View.zip" href="/downloads/TD Simple List View.zip"><strong>TD Simple List View</strong></a></p>
<p><a title="https://techiedreams.com/downloads/TD Custom List View.zip" href="/downloads/TD Custom List View.zip"><strong>TD Custom List View</strong></a></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="1" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="2" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="3" data-poid="in-632" data-post-type="none" ><a href="/gmail-like-flip-animated-multi-selection-list-view-with-action-mode/" class="wp_rp_title">Gmail like &#8211; Flip animated Multi selection list view with action mode.</a></li><li data-position="4" data-poid="in-186" data-post-type="none" ><a href="/activity-and-its-life-cycle/" class="wp_rp_title">Android Activity and its Life Cycle.</a></li><li data-position="5" data-poid="in-240" data-post-type="none" ><a href="/android-layouts-explained-with-examples/" class="wp_rp_title">Android Layouts explained with examples.</a></li></ul></div></div>
<p>The post <a href="/android-simple-custom-list-views-with-examples/">Android simple &#038; custom List views with examples.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-simple-custom-list-views-with-examples/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Android Layouts explained with examples.</title>
		<link>https://techiedreams.com/android-layouts-explained-with-examples/</link>
		<comments>https://techiedreams.com/android-layouts-explained-with-examples/#comments</comments>
		<pubDate>Thu, 08 Nov 2012 18:04:35 +0000</pubDate>
		<dc:creator><![CDATA[chanu]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Layouts]]></category>

		<guid isPermaLink="false">https://techiedreams.com/?p=240</guid>
		<description><![CDATA[<p>Android Layouts: Layouts are the design elements of any Application. Layouts in Android Provides the most basic parts of the UI. Android-SDK provides few different Layouts, basic among them are: 1. Linear Layout (Vertical &#38; Horizontal) 2. Relative Layout 3. Table Layout Other Layouts include: 4. Grid Layout 5. Frame Layout This tutorial focuses on &#8230;<br/><a class="more-link" href="/android-layouts-explained-with-examples/">Read more <span class="meta-nav">&#8594;</span></a></p><p>The post <a href="/android-layouts-explained-with-examples/">Android Layouts explained with examples.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>Android Layouts:</strong></p>
<p>Layouts are the design elements of any Application. Layouts in Android Provides the most basic parts of the UI.</p>
<p>Android-SDK provides few different Layouts, basic among them are:</p>
<p>1. Linear Layout (Vertical &amp; Horizontal)</p>
<p>2. Relative Layout</p>
<p>3. Table Layout</p>
<p>Other Layouts include:</p>
<p>4. Grid Layout</p>
<p>5. Frame Layout</p>
<p><span class="highlight-red">Note:</span> This tutorial focuses on the Basic Layouts (Linear, Relative, Table).</p>
<p>Every Layout file should generally contain a main Layout called Parent Layout. Elements added to this Layout are child&#8217;s of this layout which inherits the properties of the Parent. Each child can also have its own properties. Properties of any (child or parent) are written as &#8216;attributes&#8217; in xml &#8211; nodes.</p>
<p>All Layout files in android are grouped under a directory called &#8216;layout&#8217; which is in &#8216;res&#8217; (resource) directory of the application:</p>
<p>Project Directory &gt; res &gt; layout &gt; layout.xml</p>
<p><span style="text-decoration: underline;">Create a new Layout:</span></p>
<div class="notice">Right click on the &#8216;layout&#8217; directory &gt;<br />
Click on &#8216;New&#8217; &gt;<br />
then &#8216;Other&#8230;&#8217; &gt;<br />
In the dialog box, under &#8216;Android&#8217; directory select &#8216;Android XML File&#8217; &gt;<br />
Click &#8216;Next&#8217; &gt;<br />
Give the file a name with extension(.xml) ex: mylayout.xml,<br />
you can select a Root Element from the list<br />
(&#8216;Linear Layout&#8217; is selected by default) or directly Click on &#8216;Finish&#8217;.</div>
<p><span class="highlight-red">Note:</span> File-based resource names must contain only lowercase a-z, 0-9, or _.</p>
<p>In Android Layouts are the xml files. Android provides a Graphical Interface as well as the Code View to edit a Layout.</p>
<p>We take the basic and Mostly used Layouts and explain each of them:</p>
<p><strong>1. Linear Layout:</strong></p>
<p>As the name says all the &#8216;elements&#8217; in the Linear Layout are arranged in Linear fashion (Vertically or Horizontally).</p>
<p>We can set the orientaion of a Linear Layout by setting the &#8216;orientation&#8217; attribute to Vertical or Horizontal as shown below:</p><pre class="crayon-plain-tag">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical/horizontal" &gt;
...
...
&lt;/LinearLayout&gt;</pre><p>&nbsp;</p>
<p>Arrangement of the child&#8217;s in the Linear Layout (Vertical and Horizontal orientations) is shown below:</p>
<p><img class="alignnone size-full wp-image-247" title="linear-layout" alt="" src="/wp-content/uploads/2012/11/linear-layout.png" width="700" height="550" /></p>
<p><span style="text-decoration: underline;">Example:</span></p>
<p>Lets take an example of creating a &#8216;Simple Login Screen&#8217;. Shown below is the final Output:</p>
<p><img class="size-full wp-image-249 aligncenter" title="simple-login" alt="" src="/wp-content/uploads/2012/11/simple-login.png" width="250" height="356" /></p>
<p>Here&#8217;s the xml code to get the above layout using &#8216;Linear Layout&#8217;:</p><pre class="crayon-plain-tag">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" &gt;

&lt;TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Login"
android:textColor="#999999"
android:textSize="35dp" /&gt;

&lt;!-- Child LinearLayout 1 with horizoantal orientation --&gt;

&lt;LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal" &gt;

&lt;TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name:"
android:textColor="#999999"
android:textSize="20dp" /&gt;

&lt;EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:hint="User Name"
android:singleLine="true" /&gt;
&lt;/LinearLayout&gt;

&lt;!-- Child LinearLayout 2 with horizoantal orientation --&gt;

&lt;LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal" &gt;

&lt;TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textColor="#999999"
android:textSize="20dp" /&gt;

&lt;EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" /&gt;
&lt;/LinearLayout&gt;

&lt;Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Login" /&gt;

&lt;/LinearLayout&gt;</pre><p>&nbsp;</p>
<p><span style="text-decoration: underline;">Explanation:</span></p>
<p>The Main Linear layout or the Parent has the vertical orientation and all the child&#8217;s in the Layout are vertically aligned. For the elements &#8216;User Name&#8217; and &#8216;Password&#8217; to show their corresponding &#8216;Edit Text&#8217; boxes to the left we placed them in a separate Linear Layouts (child layouts) and gave the &#8216;horizontal&#8217; orientation.</p>
<p>Before going forward lets know about the &#8216;layout weight&#8217; property:</p>
<p>The concept of &#8216;weight&#8217; is best explained here: http://developer.android.com/training/basics/firstapp/building-ui.html#Weight</p>
<p>(after going through the above link): Alternatively we can give the &#8216;weight sum&#8217; to the parent and distribute the weight equally to all the child&#8217;s.</p>
<p><span class="highlight-green">Tip:</span> If weight sum is not specified for any layout then then &#8216;weight sum&#8217; is the sum of all the weights of the child&#8217;s.</p>
<p><strong>2. Relative Layout:</strong></p>
<p>As the name says each &#8216;element&#8217; in the Relative Layout is arranged Relative either to &#8216;parent&#8217; or to other &#8216;elements&#8217; in the Layout.</p>
<p>Relative Layout is generally defined as shown below:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" &gt;
...
...
&lt;/RelativeLayout&gt;</pre><p>&nbsp;</p>
<p>Arrangement of the child&#8217;s in the Relative Layout is shown below:</p>
<p><img class="alignnone size-full wp-image-255" title="relative-layout" alt="" src="/wp-content/uploads/2012/11/relative-layout.png" width="700" height="550" /></p>
<p><span style="text-decoration: underline;">Example:</span></p>
<p>To cleanly understand the difference in using the Linear Layout to Relative Layout and vice versa, lets take the same example of Linear Layout and create a &#8216;Simple Login Screen&#8217;. Screen shot of the final output is the same as the above.</p>
<p><img class="size-full wp-image-249 aligncenter" title="simple-login" alt="" src="/wp-content/uploads/2012/11/simple-login.png" width="250" height="356" /></p>
<p>Here&#8217;s the xml code to get the above layout using &#8216;Relative Layout&#8217;:</p><pre class="crayon-plain-tag">&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" &gt;

&lt;TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Login"
android:textColor="#999999"
android:textSize="35dp" /&gt;

&lt;!-- Child RelativeLayout 1 --&gt;

&lt;RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="20dp"
android:gravity="center" &gt;

&lt;TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name:"
android:textColor="#999999"
android:textSize="20dp" /&gt;

&lt;EditText
android:id="@+id/editText1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:hint="User Name"
android:singleLine="true" /&gt;
&lt;/RelativeLayout&gt;

&lt;!-- Child RelativeLayout 2 --&gt;

&lt;RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/relativeLayout1"
android:layout_marginTop="20dp"
android:gravity="center" &gt;

&lt;TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textColor="#999999"
android:textSize="20dp" /&gt;

&lt;EditText
android:id="@+id/editText2"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_toRightOf="@+id/textView3"
android:hint="Password"
android:inputType="textPassword" /&gt;
&lt;/RelativeLayout&gt;

&lt;Button
android:id="@+id/login"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/relativeLayout2"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Login" /&gt;

&lt;/RelativeLayout&gt;</pre><p>&nbsp;</p>
<p><span style="text-decoration: underline;">Explanation:</span></p>
<p>Here as mentioned earlier all the elements in the layout are generally aligned either relative to parent or to the other elements in the layout, example:</p>
<p>1. &#8216;id:editText1&#8242; is aligned to the right of the &#8216;id:textView2&#8242; (android:layout_toRightOf=&#8221;@+id/textView2&#8243;) &amp; we are also base lining the edit text &#8216;id:editText1&#8242; with text view &#8216;id:textView2&#8242; (android:layout_alignBaseline=&#8221;@+id/textView2&#8243;).</p>
<p>2. &#8216;id: login&#8217; Button is aligned below &#8216;id:relativeLayout2&#8242; (android:layout_below=&#8221;@+id/relativeLayout2&#8243;) &amp; it is also aligned center horizontally in the parent (android:layout_centerHorizontal=&#8221;true&#8221;).</p>
<p><strong>3. Table Layout:</strong></p>
<p>Table Layout is like any HTML Table, which contains Rows and Columns. We can customize each row by setting different properties for the row and to the row elements.</p>
<p>Table Layout is generally defined as shown below:</p><pre class="crayon-plain-tag">&lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" &gt;
...
...
&lt;/TableLayout&gt;</pre><p>&nbsp;</p>
<p>Arrangement of the child&#8217;s in the Table Layout is shown below:</p>
<p><img class="alignnone size-full wp-image-257" title="table-layout" alt="" src="/wp-content/uploads/2012/11/table-layout.png" width="700" height="550" /></p>
<p><span style="text-decoration: underline;">Example:</span></p>
<p>Lets create a Table Layout that contains different rows and columns as shown below:</p>
<p>Here&#8217;s the xml code to get the above layout using &#8216;Relative Layout&#8217;:</p><pre class="crayon-plain-tag">&lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*" &gt;

&lt;!-- Row 1 with 3 columns --&gt;

&lt;TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button1"
android:layout_weight="1"
android:text="Row 1 Column 1" /&gt;

&lt;Button
android:id="@+id/button2"
android:layout_weight="1"
android:text="Row 1 Column 2" /&gt;

&lt;Button
android:id="@+id/button3"
android:layout_weight="1"
android:text="Row 1 Column 3" /&gt;
&lt;/TableRow&gt;

&lt;!-- Row 2 with 2 columns --&gt;

&lt;TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button4"
android:text="Row 2 Column 1" /&gt;

&lt;Button
android:id="@+id/button5"
android:text="Row 2 Column 2" /&gt;
&lt;/TableRow&gt;

&lt;!-- seperator line --&gt;

&lt;View
android:layout_height="2dip"
android:background="#0000FF" /&gt;

&lt;!-- Row 3 with 1 column / column set to 2 (starts from 0) --&gt;

&lt;TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button6"
android:layout_column="2"
android:layout_weight="1"
android:text="Row 3 Column 3" /&gt;
&lt;/TableRow&gt;

&lt;!-- Row 4 with 2 columns / columns set to 1 &amp; 2 (starts from 0) --&gt;

&lt;TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button7"
android:layout_column="1"
android:layout_weight="1"
android:text="Row 4 Column 2" /&gt;

&lt;Button
android:id="@+id/button8"
android:layout_column="2"
android:layout_weight="1"
android:text="Row 4 Column 3" /&gt;
&lt;/TableRow&gt;

&lt;!-- seperator line --&gt;

&lt;View
android:layout_height="2dip"
android:background="#0000FF" /&gt;

&lt;!-- Row 5 with span = 3 --&gt;

&lt;TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button9"
android:layout_span="3"
android:layout_weight="1"
android:text="Row 5 with span = 3" /&gt;
&lt;/TableRow&gt;

&lt;!-- Row 6 with span = 2 and column set to 1 (starts form 0) --&gt;

&lt;TableRow
android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button10"
android:layout_column="1"
android:layout_span="2"
android:layout_weight="1"
android:text="Row 6 with span = 2" /&gt;
&lt;/TableRow&gt;

&lt;!-- seperator line --&gt;

&lt;View
android:layout_height="2dip"
android:background="#0000FF" /&gt;

&lt;!-- Row 7 with 2 columns and with equal weights --&gt;

&lt;TableRow
android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dip" &gt;

&lt;Button
android:id="@+id/button11"
android:layout_weight="1"
android:text="Row 7 Column 1" /&gt;

&lt;Button
android:id="@+id/button12"
android:layout_weight="1"
android:text="Row 7 Column 2" /&gt;
&lt;/TableRow&gt;

&lt;/TableLayout&gt;</pre><p>&nbsp;</p>
<p><span style="text-decoration: underline;">Explanation:</span></p>
<p>Here in the above table layout we need to know some of the properties like: layout_span and layout_column</p>
<p>layout_span: used to set the number of columns the element will occupy.</p>
<p>layout_column: used to specify the column number from which the element starts from.</p>
<p><a title="https://techiedreams.com/downloads/TD%20Counter.zip" href="/downloads/TD%20Counter.zip"><img title="20121104061143220_easyicon_cn_32" alt="" src="/wp-content/uploads/2012/11/20121104061143220_easyicon_cn_32.png" width="32" height="32" /></a> <strong>Download Sources:</strong></p>
<p><a href="/downloads/TD Layouts.zip"><strong>TD Layouts.zip</strong></a></p>

<div class="wp_rp_wrap  wp_rp_plain" ><div class="wp_rp_content"><h3 class="related_post_title">You may also like</h3><ul class="related_post wp_rp"><li data-position="0" data-poid="in-342" data-post-type="none" ><a href="/android-custom-grid-view-with-zoom-in-animation-effect/" class="wp_rp_title">Android custom Grid View with zoom-in animation effect.</a></li><li data-position="1" data-poid="in-371" data-post-type="none" ><a href="/android-simple-rss-reader/" class="wp_rp_title">Android Simple RSS Reader with Splash Screen and Custom List View.</a></li><li data-position="2" data-poid="in-424" data-post-type="none" ><a href="/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/" class="wp_rp_title">Android RSS Reader &#8211; Part Two (Offline reading, Swipe through detail views).</a></li><li data-position="3" data-poid="in-493" data-post-type="none" ><a href="/android-rss-reader-part-3-action-bar-with-animated-item/" class="wp_rp_title">Android RSS Reader &#8211; Part 3: Refresh &#8211; ActionBar item with animation&#8230;</a></li><li data-position="4" data-poid="in-578" data-post-type="none" ><a href="/android-custom-gridview-scalable-auto-adjusting-col-width/" class="wp_rp_title"> Android custom GridView scalable (auto adjusting col width).</a></li><li data-position="5" data-poid="in-302" data-post-type="none" ><a href="/android-simple-custom-list-views-with-examples/" class="wp_rp_title">Android simple &#038; custom List views with examples.</a></li></ul></div></div>
<p>The post <a href="/android-layouts-explained-with-examples/">Android Layouts explained with examples.</a> appeared first on <a href="/">TechieDreams</a>.</p>]]></content:encoded>
			<wfw:commentRss>https://techiedreams.com/android-layouts-explained-with-examples/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

 Served from: techiedreams.com @ 2015-03-15 04:55:06 by W3 Total Cache -->