Search This Blog

Showing posts with label Android Development. Show all posts
Showing posts with label Android Development. Show all posts

Friday, 14 June 2013

SlidingPaneLayout Android Example : Making customize Left to right sliding panel

SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a primary detail view for displaying content.

SlidingPaneLayout allow user to slide the content on demand. Its very helpful while we need big screen space.
This tutorial address a very simple approach to create a SlidingPaneLayout. SlidingPaneLayout  is just like a ViewSwitcher in which first child work as sliding Panel. Look at this Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sliding_pane_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!--
         The first child view becomes the left pane. When the combined
         desired width (expressed using android:layout_width) would
         not fit on-screen at once, the right pane is permitted to
         overlap the left. 
    -->

    <ListView
        android:id="@+id/left_pane"
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:layout_gravity="left" />
    <!--
         The second child becomes the right (content) pane. In this
         example, android:layout_weight is used to express that this
         pane should grow to consume leftover available space when the
         window is wide enough. This allows the content pane to
         responsively grow in width on larger screens while still
         requiring at least the minimum width expressed by
         android:layout_width.
    -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff333333" >

        <WebView
            android:id="@+id/content_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    </RelativeLayout>

</android.support.v4.widget.SlidingPaneLayout>

It can be easily customized. Above layout gives a simple vision that we can customize it on base of its child. Now lets have a look how Activity look a like

package com.example.android.supportv4.widget;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.appdata.DataUnit;
import com.example.android.supportv4.R;

public class SlidingPaneLayoutActivity extends Activity {
    private SlidingPaneLayout mSlidingLayout;
    private ListView mList;
    private WebView mContent;

    private ActionBarHelper mActionBar;

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

        setContentView(R.layout.sliding_pane_layout);

        mSlidingLayout = (SlidingPaneLayout) findViewById(R.id.sliding_pane_layout);
        mList = (ListView) findViewById(R.id.left_pane);
        mContent = (WebView) findViewById(R.id.content_text);
        mContent.setTag(findViewById(R.id.progressBar1));
        mContent.getSettings().setJavaScriptEnabled(true);
        mSlidingLayout.setPanelSlideListener(new SliderListener());
        mSlidingLayout.openPane();

        mList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.simple_list_item, DataUnit.TITLES));
        mList.setOnItemClickListener(new ListItemClickListener());

        mActionBar = createActionBarHelper();
        mActionBar.init();
        mSlidingLayout.getViewTreeObserver().addOnGlobalLayoutListener(
                new FirstLayoutListener());
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*
         * The action bar up action should open the slider if it is currently
         * closed, as the left pane contains content one level up in the
         * navigation hierarchy.
         */
        if (item.getItemId() == android.R.id.home && !mSlidingLayout.isOpen()) {
            mSlidingLayout.smoothSlideOpen();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * This list item click listener implements very simple view switching by
     * changing the primary content text. The slider is closed when a selection
     * is made to fully reveal the content.
     */
    private class ListItemClickListener implements ListView.OnItemClickListener {
        @SuppressWarnings("deprecation")
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            mContent.loadUrl(DataUnit.DIALOGUE[position]);
            mActionBar.setTitle(DataUnit.TITLES[position]);
            mSlidingLayout.smoothSlideClosed();
        }
    }

    /**
     * This panel slide listener updates the action bar accordingly for each
     * panel state.
     */
    private class SliderListener extends
            SlidingPaneLayout.SimplePanelSlideListener {
        @Override
        public void onPanelOpened(View panel) {
            mActionBar.onPanelOpened();
        }

        @Override
        public void onPanelClosed(View panel) {
            mActionBar.onPanelClosed();
        }
    }

    /**
     * This global layout listener is used to fire an event after first layout
     * occurs and then it is removed. This gives us a chance to configure parts
     * of the UI that adapt based on available space after they have had the
     * opportunity to measure and layout.
     */
    private class FirstLayoutListener implements
            ViewTreeObserver.OnGlobalLayoutListener {
        @Override
        public void onGlobalLayout() {
            mActionBar.onFirstLayout();
            mSlidingLayout.getViewTreeObserver().removeOnGlobalLayoutListener(
                    this);
        }
    }

    /**
     * Create a compatible helper that will manipulate the action bar if
     * available.
     */
    private ActionBarHelper createActionBarHelper() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new ActionBarHelperICS();
        } else {
            return new ActionBarHelper();
        }
    }

    /**
     * Stub action bar helper; this does nothing.
     */
    private class ActionBarHelper {
        public void init() {
        }

        public void onPanelClosed() {
        }

        public void onPanelOpened() {
        }

        public void onFirstLayout() {
        }

        public void setTitle(CharSequence title) {
        }
    }

    /**
     * Action bar helper for use on ICS and newer devices.
     */
    private class ActionBarHelperICS extends ActionBarHelper {
        private final ActionBar mActionBar;
        private CharSequence mDrawerTitle;
        private CharSequence mTitle;

        ActionBarHelperICS() {
            mActionBar = getActionBar();
        }

        @Override
        public void init() {
            mActionBar.setDisplayHomeAsUpEnabled(true);
            mActionBar.setHomeButtonEnabled(true);
            mTitle = mDrawerTitle = getTitle();
        }

        @Override
        public void onPanelClosed() {
            super.onPanelClosed();
            mActionBar.setDisplayHomeAsUpEnabled(true);
            mActionBar.setHomeButtonEnabled(true);
            mActionBar.setTitle(mTitle);
        }
        

        @Override
        public void onPanelOpened() {
            super.onPanelOpened();
            mActionBar.setHomeButtonEnabled(false);
            mActionBar.setDisplayHomeAsUpEnabled(false);
            mActionBar.setTitle(mDrawerTitle);
        }

        @SuppressWarnings("deprecation")
        @Override
        public void onFirstLayout() {
            if (mSlidingLayout.canSlide() && !mSlidingLayout.isOpen()) {
                onPanelClosed();
            } else {
                onPanelOpened();
            }
        }

        @Override
        public void setTitle(CharSequence title) {
            mTitle = title;
        }
    }

}


                                                       ScreenShot of this application




DownLoad Source Code



Saturday, 25 May 2013

how to debug a running application in android?

Generally, we can launch an android application in two mode 1) Running and 2) Debugging. While running an application, it works fast, faster speed allow developer to navigate android application smoothly. But while launching in debug mode, its comparatively slow. So i was searching to find a way to launch application in run mode and whenever i want, switching to debug mode. Finally i did it. so lets see

It contains only two steps

1) Launch your application in run mode , and do whatever you want to do




Step 2) Open the DDMS tool, select your device and then select your application package name of application for which you want to change the mode. And click on debug. See Screen shot



Friday, 26 April 2013

Implementing Search functionality inside Android ListView.

Listing in android contains many features that make ListView a powerful tool. Android developer are very much aware from recycling of View inside BaseAdapter. This tutorial address the issue(or say requirement) of searching inside a ListView.
Concept roam around performing search operation on Array and redraw the ListView.
Let Do this step wise



Step 1) Create one simple User interface to handle requirement search

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="5dp"
        android:background="@drawable/search_input1" >

        <Button
            android:id="@+id/btnSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="2dp"
            android:background="@drawable/cancel_search" />

        <Button
            android:id="@+id/btnLeft"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="2dp"
            android:background="@drawable/icon_search" />

        <EditText
            android:id="@+id/edSearch"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/btnSearch"
            android:layout_toRightOf="@id/btnLeft"
            android:background="@null"
            android:hint="Search"
            android:imeOptions="actionSearch"
            android:singleLine="true" />
    </RelativeLayout>

    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/top"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:cacheColorHint="@android:color/transparent"
        android:divider="@android:color/white"
        android:dividerHeight="2dp" >
    </ListView>

</RelativeLayout>

Step 2) Create One BaseAdapter to bind Data inside a ListView

package com.testsearching;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MySimpleSearchAdapter extends BaseAdapter {

    private ArrayList<String> mData = new ArrayList<String>();
    private LayoutInflater mInflater;

    public MySimpleSearchAdapter(Activity activity) {
        mInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addItem(String item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    public int getCount() {
        return mData.size();
    }

    public String getItem(int position) {
        return mData.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_one, null);
            holder.textView = (TextView) convertView.findViewById(R.id.text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String str = mData.get(position);
        holder.textView.setText(str);
        return convertView;
    }

    public class ViewHolder {
        public TextView textView;
    }

}


Step 3) Now write the Search Logic inside your activity

package com.testsearching;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class SearchFunctionality extends Activity implements OnClickListener,
        OnEditorActionListener, OnItemClickListener {
    ListView mListView;
    MySimpleSearchAdapter mAdapter;
    Button btnSearch, btnLeft;
    EditText mtxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mListView = (ListView) findViewById(R.id.mListView);
        mAdapter = new MySimpleSearchAdapter(this);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        btnLeft = (Button) findViewById(R.id.btnLeft);
        mtxt = (EditText) findViewById(R.id.edSearch);
        mtxt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (0 != mtxt.getText().length()) {
                    String spnId = mtxt.getText().toString();
                    setSearchResult(spnId);
                } else {
                    setData();
                }
            }
        });
        btnLeft.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        setData();
    }

    ArrayList<String> mAllData;

    String[] str = { "Hit me Hard", "GIJ, Rise Of Cobra", "Troy",
            "A walk To remember", "DDLJ", "Tom Peter Nmae", "David Miller",
            "Kings Eleven Punjab", "Kolkata Knight Rider", "Rest of Piece" };

    public void setData() {
        mAllData = new ArrayList<String>();
        mAdapter = new MySimpleSearchAdapter(this);
        for (int i = 0; i < str.length; i++) {
            mAdapter.addItem(str[i]);
            mAllData.add(str[i]);
        }
        mListView.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnSearch:
            mtxt.setText("");
            setData();
            break;
        case R.id.btnLeft:

            break;
        }
    }

    public void setSearchResult(String str) {
        mAdapter = new MySimpleSearchAdapter(this);
        for (String temp : mAllData) {
            if (temp.toLowerCase().contains(str.toLowerCase())) {
                mAdapter.addItem(temp);
            }
        }
        mListView.setAdapter(mAdapter);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        return false;
    }

    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        String str = mAdapter.getItem(position);
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }
}

See Above code output in form of ScreenShot






Download Source Of Application

Wednesday, 20 February 2013

Binding service using iBinder and updating UI in android

Binding service is used when you want to communicate with service either it for updating UI with the work you are doing in service or using values of service's current instance. See binding service using Messanger

You can bind service by multiple ways but here i explain using iBinder method.

Some Fact
You can only bind service with activity not with the BroadcastReceiver

Binding Purpose
To get current instance of Service to interact with its member
When to use iBinder Approach
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind()
Binding service automatically start service so use either bindService() or both methods. UsingiBinder is service class

public void startingService() {
Intent intent = new Intent(this, UsingiBinder.class);
startService(intent);
}

public void bindService() {
Intent intent = new Intent(this, UsingiBinder.class);
bindService(intent, new ConnectService(), 0);
}

ConnectService is ServiceConnection that provide you bridge between Service and activity. It has two method

onServiceConnected(ComponentName name, IBinder service)
onServiceDisconnected(ComponentName name)

Service class has method onBind(Intent arg0) that help to return service instance in the form of iBinder

 import android.app.Service;  
 import android.content.Intent;  
 import android.os.Binder;  
 import android.os.IBinder;  
 public class UsingiBinder extends Service {  
 @Override  
 public IBinder onBind(Intent arg0) {  
 return iBinder;  
 }  
 private IBinder iBinder = new ContainsLocal();  
 public class ContainsLocal extends Binder {  
 UsingiBinder getBinder() {  
 return UsingiBinder.this;  
 }  
 }  
 }  

Download All Service Binding Example

Android News and source code