Friday, 31 March 2017

Custom Toolbar in Android

STEP 1 : Create toolbar.xml in layout folder

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:background="?attr/colorPrimary">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Custom Toolbar"
            android:textSize="@dimen/toolbartext"
            android:textColor="@android:color/white"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            />

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

STEP 2 : Include toolbar in xml file where ever you want.

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

STEP 3 : Add this lines in java file

setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

ITS DONE !!!

Android Working with Google Maps


Step 1 : Install the Google Play services SDK



Step 2 : Get a Google Maps API key

Login into Google API Console, click on Credentials, then click on Create a project.

 





Then click on Create credentials and the click on API KEY


Next you will get your api key just copy it you will need this next in this project.


Now click on Libraries, Click on Google Maps Android API and ENABLE it.








STEP 3 : Creating new Project

STEP 4 : Add the line shown below in build.gradle (Module: app)



dependencies {
    .....
    compile 'com.google.android.gms:play-services:10.2.0'
    .....
}

and click on Sync Now



STEP 5 : Create activity_main.xml in layout folder

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity" />

</RelativeLayout>

STEP 6 : Modify your AndroidManifest.xml as shown below.

You need to add permission for location and you need to declare API Key in meta-data.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.mapexamplebymiraj">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="PUT YOUR API KEY HERE" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


STEP 7 : Create MainActivity.java and put the below code in it.

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    GoogleMap mMap;
    Double latitude, longitude;
    Location mLastLocation;
    GoogleApiClient googleApiClient;

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

        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        latitude = mLastLocation.getLatitude();
        longitude = mLastLocation.getLongitude();
        MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Current Location");
        mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
        Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "connection suspended", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "connection failed", Toast.LENGTH_SHORT).show();
    }
}

Now Just run the Project you are Done.

Note : You need to turn on your Location and Internet otherwise you app will crash. You can put permission check to overcome that problem.

Thursday, 30 March 2017

Button Material Design in Android



STEP 1 : Create org_one.xml under drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#f99100"
        android:endColor="#f99100"
        android:angle="45"/>
    <padding android:left="6dp"
        android:top="6dp"
        android:right="6dp"
        android:bottom="6dp" />
    <corners android:radius="30dp" />

</shape>

STEP 2 : Create org_two.xml under drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#c77400"
        android:endColor="#c77400"
        android:angle="45"/>
    <padding android:left="6dp"
        android:top="6dp"
        android:right="6dp"
        android:bottom="6dp" />
    <corners android:radius="30dp" />

</shape>

STEP 3 : Create org_btn_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/org_one" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@drawable/org_two" android:state_pressed="true"/>
</selector>

STEP 4 : Set org_btn_selector.xml in background of button

<Button
                android:id="@+id/btnregistorfree"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="10dp"
                android:background="@drawable/org_btn_selector"
                android:text="Register for Free"
                android:textColor="@color/white"
                android:textSize="12sp"/>

EditText material Design Android





STEP 1 : Create edittext.xml under drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background Color
    <solid android:color="#ffffff" />-->
    <!-- Border Color -->
    <stroke android:width="1dp" android:color="#5c6f7b" />
    <!-- Round Corners -->
    <corners android:radius="30dp" />
    <padding android:left="16dp"
        android:top="10dp"
        android:right="6dp"
        android:bottom="10dp" />
</shape>

STEP 2 : Set edittext.xml in background of EditText

You can also set drawable icon left or right if you want.

<EditText
   android:id="@+id/etunm"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="@drawable/edittext"
   android:drawableLeft="@drawable/user_icon"
   android:drawablePadding="15dp"
   android:drawableStart="@drawable/user_icon"
   android:hint="@string/uname"
   android:inputType="textEmailAddress"
   android:singleLine="true"
   android:textSize="13sp" />

Scrolling increases when you set background to SCROLLVIEW

Solution :

<ScrollView
    ......
    android:background="@drawable/signup_background"
    android:fillViewport="true"  >

Animation activity transition in android



STEP 1 : Create anim folder under res folder




STEP 2 : Create fade_in.xml under anim folder

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

STEP 3 : Create fade_out.xml under anim folder

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fillAfter="true"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

STEP 4 : Write the below code when you change from one activity to another

startActivity(new Intent(getApplicationContext(),YourActivity.class));
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);

Tab Layout in Android


STEP 1 :
Open build.gradle and add android design support library com.android.support:design:25.1.0

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


STEP 2 :

Open colors.xml located under res ⇒ values and add the below color values.

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

    <color name="colorPrimary">#125688</color>
    <color name="colorPrimaryDark">#125688</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="colorAccent">#c8e8ff</color>
   
</resources>


STEP 3 :
Add the below dimensions to dimens.xml located under res ⇒ values.
<resources>
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="tab_max_width">264dp</dimen>
<dimen name="tab_padding_bottom">16dp</dimen>
<dimen name="tab_label">14sp</dimen>
<dimen name="custom_tab_layout_height">72dp</dimen>
</resources>

STEP 4 :
Open styles.xml located under res ⇒ values and add below styles. The styles defined in this styles.xml are common to all the android versions.

<resources>

    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

STEP 5 :
Finally open AndroidManifest.xml and modify the theme to our customized theme by changing the android:theme attribute value.
android:theme="@style/MyMaterialTheme"

STEP 6 :
Under your main package create a fragment named OneFragment.java and add the below code.

public class OneFragment extends Fragment{

    public OneFragment() {

    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_one, container, false);
    }

}
STEP 7 :
Open fragment_one.xml located under res ⇒ layout and do the below changes.
<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=".OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/one"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"/>

</RelativeLayout>


STEP 8 :
Likewise create few more fragment activities with same code we used for OneFragment.java. I have created TwoFragment.java, ThreeFragment.java

STEP 9 :
Open the layout file of main activity (activity_main.xml) and add below layout code.
app:tabMode – Defines the mode of the tab layout. In our case the value should be “fixed”
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

            </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>



STEP 10 :

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

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

public class Home extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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



        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}


Note :
Import this :-
import android.support.v4.app.Fragment;

Reference :- http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
- Here you will also find how to set icons, icons and text both, etc.

Animated Progress Bar




Step 1 : Add below line in gradle 

compile 'com.github.d-max:spots-dialog:0.4@aar'


Step 2 : Add new Style in styles.xml

<resources>

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

    <style name="Custom" parent="android:Theme.DeviceDefault.Dialog">
        <item name="DialogTitleAppearance">@android:style/TextAppearance.Medium</item>
        <item name="DialogTitleText">Please Wait</item>
        <item name="DialogSpotColor">@color/colorAccent</item>
        <item name="DialogSpotCount">8</item>
    </style>

</resources>






Step 3 : Java code to add progress bar


import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import dmax.dialog.SpotsDialog;

public class MainActivity extends AppCompatActivity {

    private AlertDialog progressDialog;


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

        progressDialog = new SpotsDialog(this, R.style.Custom);


        progressDialog.show();
    }
}