Tuesday 19 April 2011

Introduction to Android development

Introduction

The BlackBerry and iPhone, which have appealing and high-volume mobile platforms, are addressing opposite ends of a spectrum. The BlackBerry is rock-solid for the enterprise business user. For a consumer device, it's hard to compete with the iPhone for ease of use and the "cool factor." Android, a young and yet-unproven platform, has the potential to play at both ends of the mobile-phone spectrum and perhaps even bridge the gulf between work and play.

Today, many network-based or network-capable appliances run a flavor of the Linux kernel. It's a solid platform: cost-effective to deploy and support and readily accepted as a good design approach for deployment. The UI for such devices is often HTML-based and viewable with a PC or Mac browser. But not every appliance needs to be controlled by a general computing device. Consider a conventional appliance, such as a stove, microwave or bread maker. What if your household appliances were controlled by Android and boasted a color touch screen? With an Android UI on the stove-top, the author might even be able to cook something.

In this article, learn about the Android platform and how it can be used for mobile and nonmobile applications. Install the Android SDK and build a simple application. Download the source code for the example application in this article.


A brief history of Android

The Android platform is the product of the Open Handset Alliance, a group of organizations collaborating to build a better mobile phone. The group, led by Google, includes mobile operators, device handset manufacturers, component manufacturers, software solution and platform providers, and marketing companies. From a software development standpoint, Android sits smack in the middle of the open source world.
The first Android-capable handset on the market was the G1 device manufactured by HTC and provisioned on T-Mobile. The device became available after almost a year of speculation, where the only software development tools available were some incrementally improving SDK releases. As the G1 release date neared, the Android team released SDK V1.0 and applications began surfacing for the new platform.
To spur innovation, Google sponsored two rounds of "Android Developer Challenges," where millions of dollars were given to top contest submissions. A few months after the G1, the Android Market was released, allowing users to browse and download applications directly to their phones. Over about 18 months, a new mobile platform entered the public arena.

The Android platform

With Android's breadth of capabilities, it would be easy to confuse it with a desktop operating system. Android is a layered environment built upon a foundation of the Linux kernel, and it includes rich functions. The UI subsystem includes:
  • Windows
  • Views
  • Widgets for displaying common elements such as edit boxes, lists, and drop-down lists
Android includes an embeddable browser built upon WebKit, the same open source browser engine powering the iPhone's Mobile Safari browser.
Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack, though not all Android devices are equipped with the required hardware. There is also camera support.
Historically, two areas where mobile applications have struggled to keep pace with their desktop counterparts are graphics/media, and data storage methods. Android addresses the graphics challenge with built-in support for 2-D and 3-D graphics, including the OpenGL library. The data-storage burden is eased because the Android platform includes the popular open source SQLite database. Figure 1 shows a simplified view of the Android software layers.

Figure 1. Android software layers






Application architecture 

As mentioned, Android runs atop a Linux kernel. Android applications are written in the Java programming language, and they run within a virtual machine (VM). It's important to note that the VM is not a JVM as you might expect, but is the Dalvik Virtual Machine, an open source technology. Each Android application runs within an instance of the Dalvik VM, which in turn resides within a Linux-kernel managed process, as shown below.
Figure 2. Dalvik VM



An Android application consists of one or more of the following classifications:
Activities
An application that has a visible UI is implemented with an activity. When a user selects an application from the home screen or application launcher, an activity is started.
Services
A service should be used for any application that needs to persist for a long time, such as a network monitor or update-checking application.
Content providers
You can think of content providers as a database server. A content provider's job is to manage access to persisted data, such as a SQLite database. If your application is very simple, you might not necessarily create a content provider. If you're building a larger application, or one that makes data available to multiple activities or applications, a content provider is the means of accessing your data.
Broadcast receivers
An Android application may be launched to process a element of data or respond to an event, such as the receipt of a text message.
An Android application, along with a file called AndroidManifest.xml, is deployed to a device. AndroidManifest.xml contains the necessary configuration information to properly install it to the device. It includes the required class names and types of events the application is able to process, and the required permissions the application needs to run. For example, if an application requires access to the network — to download a file, for example — this permission must be explicitly stated in the manifest file. Many applications may have this specific permission enabled. Such declarative security helps reduce the likelihood that a rogue application can cause damage on your device.

Required tools:

The easiest way to start developing Android applications is to download the Android SDK and the Eclipse IDE (see Resources). Android development can take place on Microsoft® Windows®, Mac OS X, or Linux.
This article assumes you are using the Eclipse IDE and the Android Developer Tools plug-in for Eclipse. Android applications are written in the Java language, but compiled and executed in the Dalvik VM (a non-Java virtual machine). Coding in the Java language within Eclipse is very intuitive; Eclipse provides a rich Java environment, including context-sensitive help and code suggestion hints. Once your Java code is compiled cleanly, the Android Developer Tools make sure the application is packaged properly, including the AndroidManifest.xml file.
It's possible to develop Android applications without Eclipse and the Android Developer Tools plug-in, but you would need to know your way around the Android SDK.
The Android SDK is distributed as a ZIP file that unpacks to a directory on your hard drive. Since there have been several SDK updates, it is recommended that you keep your development environment well organized so you can easily switch between SDK installations. The SDK includes:
android.jar
Java archive file containing all of the Android SDK classes necessary to build your application.
documention.html and docs directory
The SDK documentation is provided locally and on the Web. It's largely in the form of JavaDocs, making it easy to navigate the many packages in the SDK. The documentation also includes a high-level Development Guide and links to the broader Android community.
Samples directory
The samples subdirectory contains full source code for a variety of applications, including ApiDemo, which exercises many APIs. The sample application is a great place to explore when starting Android application development.
Tools directory
Contains all of the command-line tools to build Android applications. The most commonly employed and useful tool is the adb utility (Android Debug Bridge).
usb_driver
Directory containing the necessary drivers to connect the development environment to an Android-enabled device, such as the G1 or the Android Dev 1 unlocked development phone. These files are only required for developers using the Windows platform.
Android applications may be run on a real device or on the Android Emulator, which ships with the Android SDK. Figure 3 shows the Android Emulator's home screen.

Figure 3. Android Emulator
Android Debug Bridge 

The adb utility supports several optional command-line arguments that provide powerful features, such as copying files to and from the device. The shell command-line argument lets you connect to the phone itself and issue rudimentary shell commands. Figure 4 shows the adb shell command against a real device connected to a Windows laptop with a USB cable.

Figure 4. Using the adb shell command

Within this shell environment, you can:
  • Display the network configuration that shows multiple network connections. Note the multiple network connections:
    • lo is the local or loopback connection.
    • tiwlan0 is the WiFi connection with an address provisioned by a local DHCP server.
  • Display the contents of the PATH environment variable.
  • Execute the su command to become the super-user.
  • Change the directory to /data/app, where user applications are stored.
  • Do a directory listing where you see a single application. Android application files are actually archive files that are viewable with WinZip or equivalent. The extension is apk.
  • Issue a ping command to see if Google.com is available.
From this same command-prompt environment, you can also interact with SQLite databases, start programs, and many other system-level tasks. This is fairly remarkable function, considering you're connected to a telephone.


Coding a basic application :
This section provides a whirlwind tour of building an Android application. The example application is about as simple as you can imagine: a modified "Hello Android" application. You'll add a minor modification to make the screen background color all white so you can use the phone as a flashlight. Not very original, but it will be useful as an example. Download the full source code.
To create an application in Eclipse, select File > New > Android project, which starts the New Android Project wizard.

Figure 5. New Android project wizard
 Next, you create a simple application with a single activity, along with a UI layout stored in main.xml. The layout contains a text element you're going to modify to say Android FlashLight. The simple layout is shown below.

Listing 1. Flashlight layout
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/all_white">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" android:textColor="@color/all_black" 
   android:gravity="center_horizontal"/>
</LinearLayout>
 
Create a couple of color resources in strings.xml.

Listing 2. Color in strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Android FlashLight</string>
    <string name="app_name">FlashLight</string>
    <color name="all_white">#FFFFFF</color>
    <color name="all_black">#000000</color>
</resources>

The main screen layout has a background color defined as all_white. In the strings.xml file, you see that all_white is defined as an RGB triplet value of #FFFFFF, or all white.
The layout contains a single TextView, which is really just a piece of static text; it is not editable. The text is set to be black and is centered horizontally with the gravity attribute.
The application has a Java source file called FlashLight.java, as shown below.
 
Listing 3. Flashlight.java
package com.msi.flashlight;
import android.app.Activity;
import android.os.Bundle;
public class FlashLight extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

The code is boiler-plate directly from the New Project wizard:
  • It is part of a Java package called com.msi.flashlight.
  • It has two imports:
    • One for the activity class
    • One for the bundle class
  • When this activity is initiated, the onCreate method is invoked, passing in a savedInstanceState. Don't be concerned with this bundle for our purposes; it is used when an activity is suspended and then resumed.
  • The onCreate method is an override of the activity class method of the same name. It calls the super class's onCreate method.
  • A call to setContentView() associates the UI layout defined in the file main.xml. Anything in main.xml and strings.xml gets automatically mapped to constants defined in the R.java source file. Never edit this file directly, as it is changed upon every build.
Running the application presents a white screen with black text.




 




 




 

Friday 15 April 2011

Project Structure of Android Programming



The Android build system is organized around a specific directory tree structure for your Android project, much like any other Java project. The specifics, though, are fairly unique to Android and what it all does to prepare the actual application that will run on the device or emulator. Here's a quick primer on the project structure, to help you make sense of it all.

Root Contents

When you create a new Android project (e.g., via activityCreator.py), you
Get five key items in the project's root directory:

• AndroidManifest.xml, which is an XML file describing the application
Being built and what components – activities, services, etc. – are
Being supplied by that application

• build.xml, which is an Ant script for compiling the application and
Installing it on the device

• Bin/, which holds the application once it is compiled

• Sac/, which holds the Java source code for the application

• Res/, which holds "resources", such as icons, GUI layouts, and the
Like, that gets packaged with the compiled Java in the application

• Assets/, which hold other static files you wish packaged with the
Application for deployment onto the device

The Sweat Off Your Brow

When you created the project (e.g., via activityCreator.py), you supplied the fully-qualified class name of the "main" activity for the application (e.g., com.android.demo). You will then find that your project's src/ tree already has the namespace directory tree in place, plus a stub Activity subclass representing your main activity (e.g., src/com/ android/Demo.java). You are welcome to modify this file and add others to the src/ tree as needed to implement your application.


The first time you compile the project (e.g., via ant), out in the "main" activity's namespace directory, the Android build chain will create R.java. This contains a number of constants tied to the various resources you placed out in the res/ directory tree. You should not modify R.java yourself, letting the Android tools handle it for you. You will see throughout many of the samples where we reference things in R.java (e.g., referring to a layout's identifier via R.layout.main).

And Now, the Rest of the Part of Structure

You will also find that your project has a res/ directory tree. This holds "resources" – static files that are packaged along with your application, either in their original form or, occasionally, in a preprocessed form. Some of the subdirectories you will find or create under res/ include:

• Res/drawable/ for images (PNG, JPEG, etc.)
• Res/layout/ for XML-based UI layout specifications
• Res/raw/ for general-purpose files (e.g., a CSV file of account
Information)
• Res/values/ for strings, dimensions, and the like
• Res/xml/ for other general-purpose XML files you wish to ship

What You Get Out Of It

When you compile your project (via ant or the IDE), the results go into the
Bin/ directory under your project root. Specifically:

• bin/classes/ holds the compiled Java classes
• Bin/classes.dex holds the executable created from those compiled
Java classes
• bin/yourapp.apk is the actual Android application (where yourapp is
the name of your application)

The .apk file is a ZIP archive containing the .dex file, the compiled edition of
your resources (resources.arsc), any un-compiled resources (such as what
You put in res/raw/) and the AndroidManifest.xml file.




Inside the Manifest

The foundation for any Android application is the manifest file: Android Manifest.xml in the root of your project. Here is where you declare
What all is inside your application – the activities, the services, and so on.
You also indicate how these pieces attach themselves to the overall Android
System; for example, you indicate which activity (or activities) should appear
On the device's main menu (a.k.a., launcher).

When you create your application, you will get a starter manifest generated
For you. For a simple application, offering a single activity and nothing else,
the auto-generated manifest will probably work out fine, or perhaps require
a few minor modifications. On the other end of the spectrum, the manifest
file for the Android API demo suite is over 1,000 lines long. Your production
Android applications will probably fall somewhere in the middle.

Most of the interesting bits of the manifest will be described in greater detail in the chapters on their associated Android features. For example, the service element will be described in greater detail in the chapter on creating services. For now, we just need to understand what the role of the manifest is and its general overall construction.

In The Beginning, There Was the Root, And It
Was Good

The root of all manifest files is, not surprisingly, a manifest element:


...


Note the namespace declaration. Curiously, the generated manifests only apply it on the attributes, not the elements (e.g., it's manifest, not android: manifest). However, that pattern works, so unless Android changes, stick with their pattern.

The biggest piece of information you need to supply on the manifest element is the package attribute (also curiously not-name spaced). Here, you can provide the name of the Java package that will be considered the "base" of your application. Then, everywhere else in the manifest file that needs a class name, you can just substitute a leading dot as shorthand for the package. For example, if you needed to refer to com.joomlavogue.android.Snicklefritz in this manifest shown above, you could just use .Snicklefritz, since com.joomlavogue.android is defined as the
Application’s package.


Permissions, Instrumentations, and Applications

Underneath the manifest element, you will find:

•uses-permission elements, to indicate what permissions your application will need in order to function properly – see the chapter on permissions for more details

• permission elements, to declare permissions that activities or services might require other applications hold in order to use your application's data or logic –again, more details are forthcoming in the chapter on permissions

• instrumentation elements, to indicate code that should be invoked on key system events, such as starting up activities, for the purposes of logging or monitoring

• an application element, defining the guts of the application that the manifest describes







...

In the preceding example, the manifest has uses-permission elements to indicate some device capabilities the application will need – in this case, permissions to allow the application to determine its current location. And, there is the application element, whose contents will describe the activities, services, and whatnot that make up the bulk of the application itself.




Wednesday 13 April 2011

Android Market Changes

The Android Market is now available on the Web. Users can now find and share information about apps from their favorite browser, then purchase and download them over-the-air to their Android-powered devices. They also introduced a new feature calledBuyer’s Currency that lets you set prices for your apps separately in each of the currencies on Android Market. They are deploying this feature country-by-country over the next few months, starting with developers in the U.S. When the feature is available to you, they will notify you by email. In-app Billing is also now available on Android Market.

Making Second Hand Working In Android Analog Clock

In android We Don't Have Second Clock In Analog Clock.
So I Find This Code For That
Here is The Code


protected static final String TAG = SecondHand.class.getName();
private ImageView img;
Handler mHandler;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Thread myThread = null;

Runnable runnable = new CountDownRunner();
myThread = new Thread(runnable);
myThread.start();

}

public void doRotate() {

runOnUiThread(new Runnable() {
public void run() {
try {

Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + "::" + seconds;
Log.v("log_tag", "Log is here Time is now" + curTime);
img = (ImageView) findViewById(R.id.imgsecond);
RotateAnimation rotateAnimation = new RotateAnimation(
(seconds - 1) * 6, seconds * 6,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);

rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(1000);
rotateAnimation.setFillAfter(true);

img.startAnimation(rotateAnimation);
} catch (Exception e) {

}
}
});
}

class CountDownRunner implements Runnable {
// @Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {

doRotate();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
Log.e("log_tag", "Error is " + e.toString());
}
}
}
}



-----------------------------------------------------------------------------------------------------------
Here is The Xml File For It

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:gravity="center" android:layout_gravity="center">

<AnalogClock android:layout_width="wrap_content"
android:hand_minute="@drawable/widgetminute" android:dial="@drawable/widgetdial"
android:hand_hour="@drawable/widgethour" android:layout_height="wrap_content"
android:id="@+id/AnalogClock" android:layout_centerInParent="true">
</AnalogClock>
<ImageView android:src="@drawable/widgetseocond1" android:id="@+id/imgsecond"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>


-------------------------------------------------------------------------------------------------------------
Here the Look is


you can download the tutorial for this code here the link  Download

Thursday 7 April 2011

Make Horizontal List View Withs Button in Android

In Android API seems to be lacking a Horizontal ListView widget. Basically, what I needed was something exactly like the Gallery widget but without the center-locking feature.



My Android Horizontal ListView implementation has the following features:
  • Subclass AdapterView so I can make use of adapters
  • Fast – make use of recycled views when possible
  • Items are clickable – (accepts AdapterView.OnItemClickListener)
  • Scrollable
  • No center-locking
  • Simple – is that so much to ask?       
package com.android.horizontal;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;

public class HorizontalListViewDemo extends Activity {

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

setContentView(R.layout.listviewdemo);

HorizontialListView listview = (HorizontialListView) findViewById(R.id.listview);
listview.setAdapter(mAdapter);

}

private static String[] dataObjects = new String[] { "Button#1",
"Button#2", "Button#3", "Button#4", "Button#5", "Button#6",
"Button#7", "Button#8" };

private BaseAdapter mAdapter = new BaseAdapter() {

@Override
public int getCount() {
return dataObjects.length;
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View retval = LayoutInflater.from(parent.getContext()).inflate(
R.layout.viewitem, null);
// TextView title = (TextView) retval.findViewById(R.id.title);
// title.setText(dataObjects[position]);
final Button bt = (Button) retval.findViewById(R.id.btview);
bt.setText(dataObjects[position]);
bt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String btname;

Log.v("log_tag", "here the position of it");
Toast.makeText(HorizontalListViewDemo.this,
"button is clicked", Toast.LENGTH_SHORT).show();
Log.v("log_tag", "bt clicked");
}
});

return retval;

}

};

}
-----------------------------------------------------------------------------------------------------------
here is other class for Horizontal List view

/*
 * HorizontalListView.java
 *
 * 
 * The MIT License
 * Copyright (c) 2011 Paul Soucy (paul@dev-smart.com)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

package com.android.horizontal;

import java.util.LinkedList;
import java.util.Queue;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

public class HorizontialListView extends AdapterView<ListAdapter> {

public boolean mAlwaysOverrideTouch = true;
protected ListAdapter mAdapter;
private int mLeftViewIndex = -1;
private int mRightViewIndex = 0;
protected int mCurrentX;
protected int mNextX;
private int mMaxX = Integer.MAX_VALUE;
private int mDisplayOffset = 0;
protected Scroller mScroller;
private GestureDetector mGesture;
private Queue<View> mRemovedViewQueue = new LinkedList<View>();
private OnItemSelectedListener mOnItemSelected;
private OnItemClickListener mOnItemClicked;

public HorizontialListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
mLeftViewIndex = -1;
mRightViewIndex = 0;
mDisplayOffset = 0;
mCurrentX = 0;
mNextX = 0;
mMaxX = Integer.MAX_VALUE;
mScroller = new Scroller(getContext());
mGesture = new GestureDetector(getContext(), mOnGesture);
}
@Override
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
mOnItemSelected = listener;
Log.v("log_tag", "Message is set On Clicked");
}
@Override
public void setOnItemClickListener(AdapterView.OnItemClickListener listener){
mOnItemClicked = listener;
Log.v("log_tag", "Set on Item Clicked");
}
private DataSetObserver mDataObserver = new DataSetObserver() {

@Override
public void onChanged() {
// TODO Auto-generated method stub
super.onChanged();
}

@Override
public void onInvalidated() {
// TODO Auto-generated method stub
super.onInvalidated();
}
};

@Override
public ListAdapter getAdapter() {
return mAdapter;
}

@Override
public View getSelectedView() {
//TODO: implement
return null;
}

@Override
public void setAdapter(ListAdapter adapter) {
if(mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataObserver);
}
mAdapter = adapter;
mAdapter.registerDataSetObserver(mDataObserver);
initView();
removeAllViewsInLayout();
        requestLayout();
}

@Override
public void setSelection(int position) {
//TODO: implement
}
private void addAndMeasureChild(final View child, int viewPos) {
LayoutParams params = child.getLayoutParams();
if(params == null) {
params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}

addViewInLayout(child, viewPos, params, true);
child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
}

@Override
protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);

if(mAdapter == null){
return;
}

if(mScroller.computeScrollOffset()){
int scrollx = mScroller.getCurrX();
mNextX = scrollx;
}
if(mNextX < 0){
mNextX = 0;
mScroller.forceFinished(true);
}
if(mNextX > mMaxX) {
mNextX = mMaxX;
mScroller.forceFinished(true);
}
int dx = mCurrentX - mNextX;
removeNonVisibleItems(dx);
fillList(dx);
positionItems(dx);
mCurrentX = mNextX;
if(!mScroller.isFinished()){
post(new Runnable(){
@Override
public void run() {
requestLayout();
}
});
}
}
private void fillList(final int dx) {
int edge = 0;
View child = getChildAt(getChildCount()-1);
if(child != null) {
edge = child.getRight();
}
fillListRight(edge, dx);
edge = 0;
child = getChildAt(0);
if(child != null) {
edge = child.getLeft();
}
fillListLeft(edge, dx);
}
private void fillListRight(int rightEdge, final int dx) {
while(rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {
View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, -1);
rightEdge += child.getMeasuredWidth();
if(mRightViewIndex == mAdapter.getCount()-1){
mMaxX = mCurrentX + rightEdge - getWidth();
}
mRightViewIndex++;
}
}
private void fillListLeft(int leftEdge, final int dx) {
while(leftEdge + dx > 0 && mLeftViewIndex >= 0) {
View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, 0);
leftEdge -= child.getMeasuredWidth();
mLeftViewIndex--;
mDisplayOffset -= child.getMeasuredWidth();
}
}
private void removeNonVisibleItems(final int dx) {
View child = getChildAt(0);
while(child != null && child.getRight() + dx <= 0) {
mDisplayOffset += child.getMeasuredWidth();
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mLeftViewIndex++;
child = getChildAt(0);
}
child = getChildAt(getChildCount()-1);
while(child != null && child.getLeft() + dx >= getWidth()) {
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mRightViewIndex--;
child = getChildAt(getChildCount()-1);
}
}
private void positionItems(final int dx) {
if(getChildCount() > 0){
mDisplayOffset += dx;
int left = mDisplayOffset;
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
int childWidth = child.getMeasuredWidth();
child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
left += childWidth;
}
}
}
public synchronized void scrollTo(int x) {
mScroller.startScroll(mNextX, 0, x - mNextX, 0);
requestLayout();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = mGesture.onTouchEvent(ev);
return handled;
}
protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
synchronized(HorizontialListView.this){
mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);
}
requestLayout();
return true;
}
protected boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
return true;
}
private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

@Override
public boolean onDown(MotionEvent e) {
return HorizontialListView.this.onDown(e);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return HorizontialListView.this.onFling(e1, e2, velocityX, velocityY);
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
synchronized(HorizontialListView.this){
mNextX += (int)distanceX;
}
requestLayout();
return true;
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Rect viewRect = new Rect();
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
int left = child.getLeft();
int right = child.getRight();
int top = child.getTop();
int bottom = child.getBottom();
viewRect.set(left, top, right, bottom);
if(viewRect.contains((int)e.getX(), (int)e.getY())){
if(mOnItemClicked != null){
mOnItemClicked.onItemClick(HorizontialListView.this, child, mLeftViewIndex + 1 + i, 0);
}
if(mOnItemSelected != null){
mOnItemSelected.onItemSelected(HorizontialListView.this, child, mLeftViewIndex + 1 + i, 0);
}
break;
}
}
return true;
}
};


}
-----------------------------------------------------------------------------------------------------
this is main xml file 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#fff"
  >
  
  <com.android.horizontal.HorizontialListView  
  android:id="@+id/listview"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:background="#ddd"
  />
  
</LinearLayout>

--------------------------------------------------------------------------
here is the xml file for custom list for horizontal view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="#fff"
  >
  
  <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/btview"
  android:background="@android:drawable/btn_default"
  />
  
</LinearLayout>
-----------------------------------------------------------------------------
If any problem share with me by make comments here .