Friday 30 January 2015

Love Wallpapers Google Play Application.

Thursday 29 January 2015

ToolBar (AppCompat) Example in Android.

This project has been created in  Android Studio using Android 5.0 SDK. and This example can run in lower versions also for that i have used AppCompat library.

Screen Shot:


Note: Make sure you have added AppCompat-V7 library to your Android Studio Project as follows.
build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "materialdesignapp.ram.com.materialdesignapp"
        minSdkVersion 10
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}


Create colors.xml file under res folder and include following colors as shown below.
colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#009688</color>
    <color name="primary_dark">#00796B</color>
    <color name="accent">#9C27B0</color>
</resources>


under styles.xml include following styles as follows.
styles.xml:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
        <!-- Customize your theme here. -->
    </style>

    <style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary</item>
        <item name="colorAccent">@color/primary</item>
    </style>
</resources>


Next create values-v21 folder under res folder and copy styles.xml from values folder and paste in under values-v21 folder or create new styles.xml under values-v21 folder and include following styles as shown below.
styles.xml:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
        <!-- Customize your theme here. -->
        <!-- Main theme colors -->
        <!--   your app branding color for the app bar -->
        <item name="android:colorPrimary">@color/primary</item>
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="android:colorPrimaryDark">@color/primary_dark</item>
        <!--   theme UI controls like checkboxes and text fields -->
        <item name="android:colorAccent">@color/accent</item>
    </style>

</resources>





Next under layout folder create new xml file called apptool_bar.xml and include following code as shown below
apptool_bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary">
</android.support.v7.widget.Toolbar>


Next under activity_main.xml include apptool_bar layout using include tag as shown below.
activity_main.xml:
<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"
    tools:context=".MainActivity">

    <include
        layout="@layout/apptool_bar"
        android:id="@+id/apptool_bar">
    </include>


    <TextView
        android:text="@string/hello_world"
        android:layout_below="@+id/apptool_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


Next under MainActivity call the reference of ToolBar and set that to action bar as follows.
MainActivity.java:
package materialdesignapp.ram.com.materialdesignapp;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity {
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.apptool_bar);

        setSupportActionBar(toolbar);

    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}



 

 
 


 
 




 


 
 

 


ActionBarCompat-ShareActionBarProvider Example in Android

Screen Shots:

 In this project we used some images those are stored in assets folder. Those images you can get from the project below.

Download Android Studio Project here : click here

How to develop this project:
First we need to create menu folder under res folder and create new xml file called main_menu.xml as follows and include following code.
main_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:support="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_share"
        android:title="@string/menu_share"
        support:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        support:showAsAction="always" />

</menu>

next you need to include values(strings,colors,dimens,styles..etc,..) from above downloadable project to your project .

next under layout folder create following xml files and include following code in those xml files as follows.

activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        style="@style/Widget.SampleMessageTile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            style="@style/Widget.SampleMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/horizontal_page_margin"
            android:layout_marginRight="@dimen/horizontal_page_margin"
            android:layout_marginTop="@dimen/vertical_page_margin"
            android:layout_marginBottom="@dimen/vertical_page_margin"
            android:text="@string/intro_message" />
    </LinearLayout>
</LinearLayout>

 
item_image.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="fitCenter" />

 
item_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:textAppearance="?android:textAppearanceLarge"
    android:lineSpacingMultiplier="1.1"
    android:gravity="center" />

 
sample_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/intro_message"
        android:padding="16dp"
        android:textAppearance="?android:textAppearanceMedium"
        android:lineSpacingMultiplier="1.1"
        android:background="#fb3" />

</LinearLayout>


MainActivity.java:

package com.example.android.actionbarcompat.shareactionprovider;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.actionbarcompat.shareactionprovider.content.ContentItem;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

    // The items to be displayed in the ViewPager
    private final ArrayList<ContentItem> mItems = getSampleContent();

    // Keep reference to the ShareActionProvider from the menu
    private ShareActionProvider mShareActionProvider;

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

        // Set content view (which contains a CheeseListFragment)
        setContentView(R.layout.sample_main);

        // Retrieve the ViewPager from the content view
        ViewPager vp = (ViewPager) findViewById(R.id.viewpager);

        // Set an OnPageChangeListener so we are notified when a new item is selected
        vp.setOnPageChangeListener(mOnPageChangeListener);

        // Finally set the adapter so the ViewPager can display items
        vp.setAdapter(mPagerAdapter);
    }

    // BEGIN_INCLUDE(get_sap)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu resource
        getMenuInflater().inflate(R.menu.main_menu, menu);

        // Retrieve the share menu item
        MenuItem shareItem = menu.findItem(R.id.menu_share);

        // Now get the ShareActionProvider from the item
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);

        // Get the ViewPager's current item position and set its ShareIntent.
        int currentViewPagerItem = ((ViewPager) findViewById(R.id.viewpager)).getCurrentItem();
        setShareIntent(currentViewPagerItem);

        return super.onCreateOptionsMenu(menu);
    }
    // END_INCLUDE(get_sap)

    /**
     * A PagerAdapter which instantiates views based on the ContentItem's content type.
     */
    private final PagerAdapter mPagerAdapter = new PagerAdapter() {
        LayoutInflater mInflater;

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // Just remove the view from the ViewPager
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // Ensure that the LayoutInflater is instantiated
            if (mInflater == null) {
                mInflater = LayoutInflater.from(MainActivity.this);
            }

            // Get the item for the requested position
            final ContentItem item = mItems.get(position);

            // The view we need to inflate changes based on the type of content
            switch (item.contentType) {
                case ContentItem.CONTENT_TYPE_TEXT: {
                    // Inflate item layout for text
                    TextView tv = (TextView) mInflater
                            .inflate(R.layout.item_text, container, false);

                    // Set text content using it's resource id
                    tv.setText(item.contentResourceId);

                    // Add the view to the ViewPager
                    container.addView(tv);
                    return tv;
                }
                case ContentItem.CONTENT_TYPE_IMAGE: {
                    // Inflate item layout for images
                    ImageView iv = (ImageView) mInflater
                            .inflate(R.layout.item_image, container, false);

                    // Load the image from it's content URI
                    iv.setImageURI(item.getContentUri());

                    // Add the view to the ViewPager
                    container.addView(iv);
                    return iv;
                }
            }

            return null;
        }
    };

    private void setShareIntent(int position) {
        // BEGIN_INCLUDE(update_sap)
        if (mShareActionProvider != null) {
            // Get the currently selected item, and retrieve it's share intent
            ContentItem item = mItems.get(position);
            Intent shareIntent = item.getShareIntent(MainActivity.this);

            // Now update the ShareActionProvider with the new share intent
            mShareActionProvider.setShareIntent(shareIntent);
        }
        // END_INCLUDE(update_sap)
    }

    /**
     * A OnPageChangeListener used to update the ShareActionProvider's share intent when a new item
     * is selected in the ViewPager.
     */
    private final ViewPager.OnPageChangeListener mOnPageChangeListener
            = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // NO-OP
        }

        @Override
        public void onPageSelected(int position) {
            setShareIntent(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            // NO-OP
        }
    };

    /**
     * @return An ArrayList of ContentItem's to be displayed in this sample
     */
    static ArrayList<ContentItem> getSampleContent() {
        ArrayList<ContentItem> items = new ArrayList<ContentItem>();

        items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "photo_1.jpg"));
        items.add(new ContentItem(ContentItem.CONTENT_TYPE_TEXT, R.string.quote_1));
        items.add(new ContentItem(ContentItem.CONTENT_TYPE_TEXT, R.string.quote_2));
        items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "photo_2.jpg"));
        items.add(new ContentItem(ContentItem.CONTENT_TYPE_TEXT, R.string.quote_3));
        items.add(new ContentItem(ContentItem.CONTENT_TYPE_IMAGE, "photo_3.jpg"));

        return items;
    }

}


AndroidManifest.xml:
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.actionbarcompat.shareactionprovider"
    android:versionCode="1"
    android:versionName="1.0">

    <!--
        ActionBarCompat provides an Action Bar from API v7 onwards
    -->
    <!-- Min/target SDK versions (<uses-sdk>) managed by build.gradle -->

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat"
        android:allowBackup="true">

        <activity
            android:name=".MainActivity">
            <!-- Launcher Intent filter -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- ContentProvider which serves files from this application's asset folder -->
        <provider
            android:name=".content.AssetProvider"
            android:authorities="com.example.android.actionbarcompat.shareactionprovider"
            android:grantUriPermissions="true"
            android:exported="true" />

    </application>

</manifest>
 









Tuesday 27 January 2015

Showing and Hiding Password in EditText in Android

Screen Shots:



activity_main.xml:
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/editText_password"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Enter Password" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Password"
        android:id="@+id/checkBox_showPassword"
        android:layout_below="@+id/editText_password"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

 
MainActivity.java:
package showhideedittext.ram.com.showhideedittextpassword;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //To setup user interface
        final EditText editPassword = (EditText) findViewById(R.id.editText_password);
        CheckBox showPassCheckBox = (CheckBox) findViewById(R.id.checkBox_showPassword);

        //Event Handling for CheckBox
        showPassCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    //To show password
                    editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //To hide Password
                    editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
    }


}

 

Friday 23 January 2015

ActionBarCompat-ListPopupMenu Example in Android

Download eclipse project from here : ActionBarCompat_listPopupMenu.zip

you need add latest AppCompat-v7 library to your project.

Get icons from attached projects drawable folders.

Screen Shots:


Create menu folder under res folder and create popup.xml under menu folder and include following code.
popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_remove"
        android:title="@string/menu_remove"/>

</menu>


strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ActionBarCompat-ListPopupMenu</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_remove">Remove</string>
    <string name="content_open_popup">Open Popup Menu</string>
    <string name="intro_message">
<![CDATA[
       
           
            This sample shows you how to use {@link android.support.v7.widget.PopupMenu PopupMenu}
            from ActionBarCompat to create a list, with each item having a dropdown menu.
           
       
        ]]>
    </string>

</resources>


styles.xml:
<resources>

    <!-- Activity themes -->

    <style name="Theme.Base" parent="android:Theme.Light" />

    <style name="Theme.Sample" parent="Theme.Base" />

    <style name="AppTheme" parent="Theme.Sample" />
    <!-- Widget styling -->

    <style name="Widget" />

    <style name="Widget.SampleMessage">
        <item name="android:textAppearance">?android:textAppearanceMedium</item>
        <item name="android:lineSpacingMultiplier">1.1</item>
    </style>

    <style name="Widget.SampleMessageTile">
        <item name="android:background">@drawable/tile</item>
        <item name="android:shadowColor">#7F000000</item>
        <item name="android:shadowDy">-3.5</item>
        <item name="android:shadowRadius">2</item>
    </style>

</resources
>

template-dimens.xml:
<resources>

    <!-- Define standard dimensions to comply with Holo-style grids and rhythm. -->

    <dimen name="margin_tiny">4dp</dimen>
    <dimen name="margin_small">8dp</dimen>
    <dimen name="margin_medium">16dp</dimen>
    <dimen name="margin_large">32dp</dimen>
    <dimen name="margin_huge">64dp</dimen>

    <!-- Semantic definitions -->

    <dimen name="horizontal_page_margin">@dimen/margin_medium</dimen>
    <dimen name="vertical_page_margin">@dimen/margin_medium</dimen>

</resources>


activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        style="@style/Widget.SampleMessageTile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            style="@style/Widget.SampleMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/vertical_page_margin"
            android:layout_marginLeft="@dimen/horizontal_page_margin"
            android:layout_marginRight="@dimen/horizontal_page_margin"
            android:layout_marginTop="@dimen/vertical_page_margin"
            android:text="@string/intro_message" />
    </LinearLayout>

</LinearLayout>


list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?attr/listPreferredItemHeight"
    android:orientation="horizontal" >

    <TextView
        android:id="@android:id/text1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:maxLines="1"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/button_popup"
        android:layout_width="56dip"
        android:layout_height="match_parent"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/content_open_popup"
        android:src="@drawable/ic_overflow" />

</LinearLayout>


sample_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.ram.actionbarcompat_listpopupmenu.PopupListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />



Cheeses.java:
package com.ram.actionbarcompat_listpopupmenu;

public class Cheeses
{
    public static final String[] CHEESES =
    { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
            "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag",
            "Airedale", "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert",
            "American Cheese", "Ami du Chambertin", "Anejo Enchilado",
            "Anneau du Vic-Bilh", "Anthoriro", "Appenzell", "Aragon", "Ardi Gasna",
            "Ardrahan", "Armenian String", "Aromes au Gene de Marc", "Asadero", "Asiago",
            "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss", "Babybel",
            "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
            "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese",
            "Bavarian Bergkase", "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue"
             };
}


PopupListFragment.java:
package com.ram.actionbarcompat_listpopupmenu;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * This ListFragment displays a list of cheeses, with a clickable view on each
 * item whichs displays a {@link android.support.v7.widget.PopupMenu PopupMenu}
 * when clicked, allowing the user to remove the item from the list.
 */
public class PopupListFragment extends ListFragment implements View.OnClickListener
{

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

        // We want to allow modifications to the list so copy the dummy data
        // array into an ArrayList
        ArrayList<String> items = new ArrayList<String>();
        for (int i = 0, z = Cheeses.CHEESES.length; i < z; i++)
        {
            items.add(Cheeses.CHEESES[i]);
        }

        // Set the ListAdapter
        setListAdapter(new PopupAdapter(items));
    }

    @Override
    public void onListItemClick(ListView listView, View v, int position, long id)
    {
        String item = (String) listView.getItemAtPosition(position);

        // Show a toast if the user clicks on an item
        Toast.makeText(getActivity(), "Item Clicked: " + item, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(final View view)
    {
        // We need to post a Runnable to show the popup to make sure that the
        // PopupMenu is
        // correctly positioned. The reason being that the view may change
        // position before the
        // PopupMenu is shown.
        view.post(new Runnable()
        {
            @Override
            public void run()
            {
                showPopupMenu(view);
            }
        });
    }

    // BEGIN_INCLUDE(show_popup)
    private void showPopupMenu(View view)
    {
        final PopupAdapter adapter = (PopupAdapter) getListAdapter();

        // Retrieve the clicked item from view's tag
        final String item = (String) view.getTag();

        // Create a PopupMenu, giving it the clicked view for an anchor
        PopupMenu popup = new PopupMenu(getActivity(), view);

        // Inflate our menu resource into the PopupMenu's Menu
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        // Set a listener so we are notified if a menu item is clicked
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
        {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem)
            {
                switch (menuItem.getItemId())
                {
                case R.id.menu_remove:
                    // Remove the item from the adapter
                    adapter.remove(item);
                    return true;
                }
                return false;
            }
        });

        // Finally show the PopupMenu
        popup.show();
    }

    // END_INCLUDE(show_popup)

    /**
     * A simple array adapter that creates a list of cheeses.
     */
    class PopupAdapter extends ArrayAdapter<String>
    {

        PopupAdapter(ArrayList<String> items)
        {
            super(getActivity(), R.layout.list_item, android.R.id.text1, items);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup container)
        {
            // Let ArrayAdapter inflate the layout and set the text
            View view = super.getView(position, convertView, container);

            // BEGIN_INCLUDE(button_popup)
            // Retrieve the popup button from the inflated view
            View popupButton = view.findViewById(R.id.button_popup);

            // Set the item as the button's tag so it can be retrieved later
            popupButton.setTag(getItem(position));

            // Set the fragment instance as the OnClickListener
            popupButton.setOnClickListener(PopupListFragment.this);
            // END_INCLUDE(button_popup)

            // Finally return the view to be displayed
            return view;
        }
    }

}


MainActivity.java:
package com.ram.actionbarcompat_listpopupmenu;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

/**
 * This sample shows you how to use {@link android.support.v7.widget.PopupMenu
 * PopupMenu} from ActionBarCompat to create a list, with each item having a
 * dropdown menu.
 * <p>
 * The interesting part of this sample is in {@link PopupListFragment}.
 *
 * This Activity extends from {@link ActionBarActivity}, which provides all of
 * the function necessary to display a compatible Action Bar on devices running
 * Android v2.1+.
 */
public class MainActivity extends ActionBarActivity
{

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

        // Set content view (which contains a PopupListFragment)
        setContentView(R.layout.sample_main);
      
      
    }

}
 

Monday 19 January 2015

ActionBarCompat Basic Example

Download eclipse project here : ActionBarCompatBasic.zip

After importing or creating project you need to add support_v7 library.

Source Website : http://developer.android.com/index.html

Screen Shots:

strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ActionBarCompat Basic</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_refresh">Refresh</string>
    <string name="menu_location">Location</string>
    <string name="menu_settings">Settings</string>
    <string name="intro_message">
<![CDATA[
       
           
            This sample shows you how to use ActionBarCompat to create a basic Activity which
            displays action items. It covers inflating items from a menu resource, as well as adding
            an item in code. Items that are not shown as action items on the Action Bar are
            displayed in the action bar overflow.
           
       
        ]]>
    </string>

</resources>

Create ids.xml under values folder and include following code:
ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

<!--         Generate an id which can be used when the location menu item is added in MainActivity -->
    <item name="menu_location" type="id"/>

</resources>

 Styles.xml:
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

 
template-dimens.xml:
<resources>

    <!-- Define standard dimensions to comply with Holo-style grids and rhythm. -->

    <dimen name="margin_tiny">4dp</dimen>
    <dimen name="margin_small">8dp</dimen>
    <dimen name="margin_medium">16dp</dimen>
    <dimen name="margin_large">32dp</dimen>
    <dimen name="margin_huge">64dp</dimen>

    <!-- Semantic definitions -->

    <dimen name="horizontal_page_margin">@dimen/margin_medium</dimen>
    <dimen name="vertical_page_margin">@dimen/margin_medium</dimen>

</resources>

template-styles.xml:
<resources>

    <!-- Activity themes -->

    <style name="Theme.Base" parent="android:Theme.Light" />

    <style name="Theme.Sample" parent="Theme.Base" />

    <style name="AppTheme" parent="Theme.Sample" />
    <!-- Widget styling -->

    <style name="Widget" />

    <style name="Widget.SampleMessage">
        <item name="android:textAppearance">?android:textAppearanceMedium</item>
        <item name="android:lineSpacingMultiplier">1.1</item>
    </style>

    <style name="Widget.SampleMessageTile">
        <item name="android:background">@drawable/tile</item>
        <item name="android:shadowColor">#7F000000</item>
        <item name="android:shadowDy">-3.5</item>
        <item name="android:shadowRadius">2</item>
    </style>

</resources> 

Create menu folder under res folder and create main.xml under menu folder and include following code:
 main.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--
    As we're using ActionBarCompat, any action item attributes come from ActionBarCompat's XML
    namespace instead of the android namespace. Here we've added a new support namespace added to
    the menu element allowing us to use the 'showAsAction' attribute in a backwards compatible way.
    Any other action item attributes used should be referenced from this namespace too
    (actionProviderClass, actionViewClass, actionLayout).
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:support="http://schemas.android.com/apk/res-auto" >

    <!--
        Here we create an item, setting support:showAsAction to display the item as an action if
        there's room on the compatible Action Bar.
    -->
    <item
        android:id="@+id/menu_refresh"
        android:icon="@drawable/ic_action_refresh"
        android:title="@string/menu_refresh"
        support:showAsAction="ifRoom"/>

    <!-- Location item is added in onCreateOptionsMenu() -->


    <!--
        Here we set the settings item to always be in the overflow menu, by setting
        support:showAsAction to never, so it is never displayed as an action item on the compatible
        Action Bar.
    -->
    <item
        android:id="@+id/menu_settings"
        android:icon="@drawable/ic_action_settings"
        android:title="@string/menu_settings"
        support:showAsAction="never"/>

</menu>

layout folder files:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        style="@style/Widget.SampleMessageTile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            style="@style/Widget.SampleMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/vertical_page_margin"
            android:layout_marginLeft="@dimen/horizontal_page_margin"
            android:layout_marginRight="@dimen/horizontal_page_margin"
            android:layout_marginTop="@dimen/vertical_page_margin"
            android:text="@string/intro_message" />
    </LinearLayout>

</LinearLayout>

sample_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="16dp"
    android:text="@string/intro_message" />

MainActivity.java:
package com.ram.actionbarcompatbasic;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

/**
 * This sample shows you how to use ActionBarCompat to create a basic Activity
 * which displays action items. It covers inflating items from a menu resource,
 * as well as adding an item in code.
 *
 * This Activity extends from {@link ActionBarActivity}, which provides all of
 * the function necessary to display a compatible Action Bar on devices running
 * Android v2.1+.
 */
public class MainActivity extends ActionBarActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_main);
    }

    // BEGIN_INCLUDE(create_menu)
    /**
     * Use this method to instantiate your menu, and add your items to it. You
     * should return true if you have added items to it and want the menu to be
     * displayed.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate our menu from the resources by using the menu inflater.
        getMenuInflater().inflate(R.menu.main, menu);

        // It is also possible add items here. Use a generated id from
        // resources (ids.xml) to ensure that all menu ids are distinct.
        MenuItem locationItem = menu
                .add(0, R.id.menu_location, 0, R.string.menu_location);
        locationItem.setIcon(R.drawable.ic_action_location);

        // Need to use MenuItemCompat methods to call any action item related
        // methods
        MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);

        return true;
    }

    // END_INCLUDE(create_menu)

    // BEGIN_INCLUDE(menu_item_selected)
    /**
     * This method is called when one of the menu items to selected. These items
     * can be on the Action Bar, the overflow menu, or the standard options
     * menu. You should return true if you handle the selection.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.menu_refresh:
            // Here we might start a background refresh task
            return true;

        case R.id.menu_location:
            // Here we might call LocationManager.requestLocationUpdates()
            return true;

        case R.id.menu_settings:
            // Here we would open up our settings activity
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    // END_INCLUDE(menu_item_selected)
}

 
 
 

 

Call Logs Sender app

 https://play.google.com/store/apps/details?id=com.ram.callssender

Using above application you can send call logs from android mobile to any other mobile as a message. You can activate services to send incoming or outgoing or both call logs information.


Saturday 3 January 2015

ImageView in Android

Used images in this project:

ScreenShots:

activity_main.xml:
<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"
    tools:context="${packageName}.${activityClass}" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        android:src="@drawable/dog" />

    <Button
        android:id="@+id/button_changeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="Change Image" />

</RelativeLayout>


MainActivity.java:
package com.ram.imageview;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final ImageView imageView = (ImageView)findViewById(R.id.imageView);
        
        Button changeButton =(Button)findViewById(R.id.button_changeImage);
        changeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
 
imageView.setImageResource(R.drawable.cat);
}
});
    }
}

Switch Example in Android

activity_main.xml:
<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"
    tools:context="${packageName}.${activityClass}" >

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="62dp"
        android:text="Switch" />

</RelativeLayout>


MainActivity.java:
package com.ram.switchexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Switch switch1 = (Switch)findViewById(R.id.switch1);
        
        switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
Toast.makeText(getApplicationContext(), "ON", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_LONG).show();
}
}
});
    }
}