Monday, 29 May 2017

Volley in Android

Login webservice volley demo :


private void login() {
    nm = uname.getText().toString().trim();
    pass = password.getText().toString().trim();
    pdialog = new ProgressDialog(Login.this);
    pdialog.setMessage("Please wait...");
    if (nm.equals("")) {
        uname.setError("email required");
    } else if (pass.equals("")) {
        password.setError("password required");
    } else {
        isInternet = ie.isInternetAvailable();
        if (isInternet) {
            pdialog.show();
            JSONObject jsonObject = new JSONObject();
            try {
                JSONObject login_info = new JSONObject();
                login_info.put("user_name", nm);
                login_info.put("password", pass);
                login_info.put("device_token", regid);
                login_info.put("device_type", "0");
                jsonObject.accumulate("method", "sign_in");
                jsonObject.accumulate("params", login_info);

            } catch (Exception e) {
                Log.d("InputStream", e.getLocalizedMessage());
            }
            JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, Config.URL, jsonObject,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                String loginresult = response.optString("success").toString();
                                if (loginresult.equals("true")) {
                                    JSONObject businessObject = response.getJSONObject("params");
                                    JSONObject businessObject1 = businessObject.getJSONObject("user_details");
                                    String salesmanid = businessObject1.getString("sales_id");
                                    // Toast.makeText(Login.this, "sales man id :- "+salesmanid , Toast.LENGTH_SHORT).show();
                                    //Toast.makeText(Login.this, "login success", Toast.LENGTH_SHORT).show();
                                    pref = new preference(getApplicationContext());
                                    pref.setLoginStatus(true);
                                    pref.setUserName(nm);
                                    pref.setSalesId(salesmanid);
                                    pdialog.dismiss();
                                    startActivity(new Intent(getApplicationContext(), Home.class));
                                    finish();
                                } else if (loginresult.equals("false")){
                                    Toast.makeText(getApplicationContext(), "Invalid Username or Password", Toast.LENGTH_SHORT).show();
                                    pdialog.dismiss();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            pdialog.dismiss();
                            Toast.makeText(Login.this, "Response error", Toast.LENGTH_SHORT).show();
                            error.printStackTrace();
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        } else {
            Toast.makeText(this, "Internet not available.", Toast.LENGTH_SHORT).show();
        }
    }
}

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();
    }
}

Tuesday, 10 January 2017

Recycler View in Android


STEP 1 :

compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:design:25.0.1'

STEP 2 :
Create custom_layout.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="wrap_content"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:orientation="vertical">



    <android.support.v7.widget.CardView

        android:id="@+id/card"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        app:cardBackgroundColor="@color/colorPrimary"

        app:cardUseCompatPadding="true"

        >



        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:orientation="vertical">



            <TextView

                android:id="@+id/tname"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:textSize="20sp"

                android:text="Name"/>



            <Button

                android:text="Button"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:id="@+id/btn1" />



            <Button

                android:text="Button"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:id="@+id/btn2" />



            <TextView

                android:id="@+id/taddress"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:textSize="20sp"

                android:text="address"/>



        </LinearLayout>

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



</LinearLayout>
STEP 3 : Create activity_main.xml
<?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">



  <android.support.v7.widget.RecyclerView

      android:id="@+id/recycler"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:scrollbars="vertical"/>

</RelativeLayout>


STEP 4 : create package GetSet and adapter

STEP 5 : Create User.java in GetSet
package com.app.ydoodle.customadapter.getset;



public class user {

    String name;

    String address;



    public String getId() {

        return id;

    }



    public void setId(String id) {

        this.id = id;

    }



    String id;



    public String getAddress() {

        return address;

    }



    public void setAddress(String address) {

        this.address = address;

    }



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }

}


Step 6 : Create CustomViewHolder.java inside adapter folder
package com.app.ydoodle.customadapter.adapter;



import android.support.v7.widget.CardView;

import android.support.v7.widget.RecyclerView;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;



import com.app.ydoodle.customadapter.R;



public class CustomViewHolder extends RecyclerView.ViewHolder {

    CardView card;

    TextView name,address;

    Button b1,b2;



    public CustomViewHolder(View itemView) {

        super(itemView);

        name = (TextView) itemView.findViewById(R.id.tname);

        address = (TextView) itemView.findViewById(R.id.taddress);

        card = (CardView) itemView.findViewById(R.id.card);

        b1= (Button) itemView.findViewById(R.id.btn1);

        b2= (Button) itemView.findViewById(R.id.btn2);







    }

}

Step 7 : create RecyclerAdapter.java
package com.app.ydoodle.customadapter.adapter;



import android.content.Context;

import android.support.v7.widget.RecyclerView;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Toast;



import com.app.ydoodle.customadapter.R;

import com.app.ydoodle.customadapter.getset.user;



import java.util.List;



public class RecyclerAdapter extends RecyclerView.Adapter<CustomViewHolder> {



    Context mContext;

    List<user> feedItem;



    public RecyclerAdapter(Context mContext, List<user> feedItem) {

        this.mContext = mContext;

        this.feedItem = feedItem;

    }



    @Override

    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout, parent, false);

        CustomViewHolder holder = new CustomViewHolder(view);

        return holder;

    }



    @Override

    public void onBindViewHolder(CustomViewHolder holder, int position) {

        final user u = feedItem.get(position);

        holder.name.setText(u.getName());

        holder.address.setText(u.getAddress());



        holder.card.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Toast.makeText(mContext, "Clicked : " + u.getId(), Toast.LENGTH_SHORT).show();

            }

        });



        holder.b1.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(mContext, "b1 :" + u.getId(), Toast.LENGTH_SHORT).show();

            }

        });





    }



    @Override

    public int getItemCount() {

        return feedItem.size();

    }

}


Step 8 : MainActivity.java
package com.app.ydoodle.customadapter;



import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import android.util.Log;



import com.app.ydoodle.customadapter.adapter.RecyclerAdapter;

import com.app.ydoodle.customadapter.getset.user;



import java.util.ArrayList;

import java.util.List;



public class MainActivity extends AppCompatActivity {



    RecyclerView recyclerView;



    List<user> detail;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);

        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));



        detail = new ArrayList<>();





        for (int i = 0; i < 20; i++) {

            user u = new user();

            u.setName("Miraj");

            u.setAddress("Jungi");

            u.setId(String.valueOf(i));

            detail.add(u);

            Log.i("testing :" , String.valueOf(i));

        }



        RecyclerAdapter adapter = new RecyclerAdapter(MainActivity.this, detail);

        recyclerView.setAdapter(adapter);



    }

}


Monday, 9 January 2017

Change Toolbar Title in Android


Write this in onCrete() :-

getSupportActionBar().setTitle("Your Title");

Sunday, 8 January 2017

Navigation Drawer in Andorid



STEP 1 :

  compile 'com.android.support:design:25.1.0'

STEP 2 :
Right click on res folder ->New -> Android resource directory ->Select Resource type to menu and click enter to create menu directory under res folder

STEP 3 :
Create a  menu/drawer_view.xml file: 

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_first_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="First" />
        <item
            android:id="@+id/nav_second_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="Second" />
        <item
            android:id="@+id/nav_third_fragment"
            android:icon="@mipmap/ic_launcher"
            android:title="Third" />
    </group>
</menu>
 
STEP 4 :
Create a new layout file res/layout/toolbar.xml with the following code:

<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/colorPrimaryDark">
</android.support.v7.widget.Toolbar>

STEP 5 :
Create nav_header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="@drawable/back"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MiHome"
        android:textColor="@android:color/white"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textSize="30dp"
        android:id="@+id/textView2"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

STEP 6 :

Setup Drawer in Activity
Next, let's setup a basic navigation drawer based on the following layout file which has the entire drawer setup in res/layout/activity_main.xml. Note that the Toolbar is added as the first child of the main content view by adding the include tag.

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

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <!-- The navigation drawer that comes from the left -->
    <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/nav_header"/>

</android.support.v4.widget.DrawerLayout>
 
STEP 7 :

In your res/values/strings.xml add the following:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>
</resources>

STEP 8 :
create OneFragment.java TwoFragment.java and ThreeFragment.java

fragment_one.xml

<?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: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>

OneFragment.java

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class OneFragment extends Fragment{
    public OneFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

STEP 9 :
Now, let's setup the drawer in our activity. We can also setup the menu icon too.

package com.example.admin.navigationdrawer;
import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.Fragmentanager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;

    // Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
    // The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        nvDrawer = (NavigationView) findViewById(R.id.nvView);
        // Setup drawer view
        setupDrawerContent(nvDrawer);
        drawerToggle = setupDrawerToggle();
        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        // NOTE: Make sure you pass in a valid toolbar reference.  ActionBarDrawToggle() does not require it
        // and will not render the hamburger icon without it.
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_openR.string.drawer_close);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;
        switch(menuItem.getItemId()) {
            case R.id.nav_first_fragment:
                fragmentClass = OneFragment.class;
                break;
            case R.id.nav_second_fragment:
                fragmentClass = TwoFragment.class;
                break;
            case R.id.nav_third_fragment:
                fragmentClass = ThreeFragment.class;
                break;
            default:
                fragmentClass = OneFragment.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


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