Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday 29 December 2016

Difference between two date in android



package com.samset.user.sample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {


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

        String first="12/29/2016 09:29:58 AM"
        String second="12/29/2016 09:29:58 PM"

        String SubscriptionEndTime = first;
        String currentTime = "12/29/2016 04:31:48 PM";

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.ENGLISH);

        try {
            Date date = dateFormat.parse(currentTime);
            Date date1 = dateFormat.parse(SubscriptionEndTime);

             Log.d("difference>>>",computeDiff(date,date1).toString());


        } catch (ParseException e) {
            e.printStackTrace();
        }

    }


    public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
        long diffInMillies = date2.getTime() - date1.getTime();
        List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
        Collections.reverse(units);
        Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
        long milliesRest = diffInMillies;
        for ( TimeUnit unit : units ) {
            long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
            long diffInMilliesForUnit = unit.toMillis(diff);
            milliesRest = milliesRest - diffInMilliesForUnit;
            result.put(unit,diff);
        }
        return result;
    }

}


output:-

Result 1:-  difference>>>:

DAYS=0,
HOURS=-7,
MINUTES=-1,
SECONDS=-50,
MILLISECONDS=0,
MICROSECONDS=0,
NANOSECONDS=0


Result 2:- difference>>>:

DAYS=0,
HOURS=4,
 MINUTES=58,
 SECONDS=10,
 MILLISECONDS=0,
 MICROSECONDS=0,
 NANOSECONDS=0



Monday 26 December 2016

Android icon size



Launcher icons    
                             
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)

Action bar, Dialog & Tab icons

24 × 24 area in 32 × 32 (mdpi)
36 × 36 area in 48 × 48 (hdpi)
48 × 48 area in 64 × 64 (xhdpi)
72 × 72 area in 96 × 96 (xxhdpi)
96 × 96 area in 128 × 128 (xxxhdpi)
Optical image size 24dip

Small Contextual Icons

16 × 16 (mdpi)
24 × 24 (hdpi)
32 × 32 (xhdpi)
48 × 48 (xxhdpi)
64 × 64 (xxxhdpi)
Optical image size 16dip

SH1 release and debug mode in android


Hello friends

Debug mode

keytool -list -alias androiddebugkey -keystore "C:\Users\user\Desktop\tickeystore.keystore" -storepass android -keypass android

above highlighted point replace your keystore path


When you are upload sign apk in play store then need to generate release mode sh1 code 

Release mode

keytool -list -alias Tiktokgames -keystore "C:/Users/user/Desktop/tickeystore.jks" -storepass indian -keypass indian


above highlighted point replace your keystore path

Thank you

Saturday 10 December 2016

Sectional recyclerview android

Hello friends
Today i am introduced how to make sectional recyclerview without use any external library
If you search in google sectional recyclerview then you find more sample with external lib but i am find better solution. So lets start and improve our programming performance....

activity_main.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="wrap_content"
    android:padding="10dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

ActvityMain.java

package com.samset.headerrecyclerviewsample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;

import com.samset.headerrecyclerviewsample.adapter.SectionalAdapter;
import com.samset.headerrecyclerviewsample.model.model.CountryState;

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

public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onStart() {
        super.onStart();

        SectionalAdapter adapter = new SectionalAdapter(getData());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);
    }

    public List<CountryState> getData() {
        List<CountryState> list = new ArrayList<>();

        list.add(new CountryState("India", null, CountryState.COUNTRY_TYPE));
        list.add(new CountryState("Allahabad", "1", CountryState.CITY_TYPE));
        list.add(new CountryState("Bharatpur", "2", CountryState.CITY_TYPE));
        list.add(new CountryState("Patna", "3", CountryState.CITY_TYPE));
        list.add(new CountryState("Mumbai", "4", CountryState.CITY_TYPE));
        list.add(new CountryState("Jaipur", "5", CountryState.CITY_TYPE));

        list.add(new CountryState("Pakistan", null, CountryState.COUNTRY_TYPE));
        list.add(new CountryState("Karachi", "6", CountryState.CITY_TYPE));
        list.add(new CountryState("Ishlamabad", "7", CountryState.CITY_TYPE));
        list.add(new CountryState("Bluechistan", "8", CountryState.CITY_TYPE));
        list.add(new CountryState("Sindhu", "9", CountryState.CITY_TYPE));
       
        list.add(new CountryState("Russiya", null, CountryState.COUNTRY_TYPE));
        list.add(new CountryState("Mascow", "10", CountryState.CITY_TYPE));
        list.add(new CountryState("Abaza", "11", CountryState.CITY_TYPE));
        list.add(new CountryState("Baley", "12", CountryState.CITY_TYPE));
        list.add(new CountryState("Barysh", "13", CountryState.CITY_TYPE));
        list.add(new CountryState("Bely", "14", CountryState.CITY_TYPE));
        list.add(new CountryState("Bobrov", "15", CountryState.CITY_TYPE));
        list.add(new CountryState("Dolinsk", "16", CountryState.CITY_TYPE));

        return list;
    }
}

SectionalAdapter.java

package com.samset.headerrecyclerviewsample.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.samset.headerrecyclerviewsample.R;
import com.samset.headerrecyclerviewsample.model.model.CountryState;

import java.util.List;

public class SectionalAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public final int CITY_TYPE = 0;
    public final int COUNTRY_TYPE = 1;
    private List<CountryState> mList;

    public SectionalAdapter(List<CountryState> list) {
        this.mList = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        switch (viewType) {
            case COUNTRY_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.section, parent, false);
                return new CountryViewHolder(view);
            case CITY_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.section_child, parent, false);
                return new CityViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        CountryState object = mList.get(position);
        if (object != null) {
            switch (object.getType()) {
                case COUNTRY_TYPE:
                    ((CountryViewHolder) holder).tvCountryName.setText(object.getName());
                    break;
                case CITY_TYPE:
                    ((CityViewHolder) holder).tvCityName.setText(object.getName());
                    //((CityViewHolder) holder).id.setText(object.getDescription());
                    break;
            }
        }
    }

    @Override
    public int getItemCount() {
        if (mList == null)
            return 0;
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mList != null) {
            CountryState object = mList.get(position);
            if (object != null) {
                return object.getType();
            }
        }
        return 0;
    }

    public static class CountryViewHolder extends RecyclerView.ViewHolder {
        private TextView tvCountryName;

        public CountryViewHolder(View itemView) {
            super(itemView);
            tvCountryName = (TextView) itemView.findViewById(R.id.titleTextView);
        }
    }

    public static class CityViewHolder extends RecyclerView.ViewHolder {
        private TextView tvCityName;
        private TextView id;

        public CityViewHolder(View itemView) {
            super(itemView);
            tvCityName = (TextView) itemView.findViewById(R.id.titleTextView);

        }
    }
}

section.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"
    android:layout_margin="5dp"
    android:orientation="vertical">

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#d7666666" />

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="Section"
        android:textSize="22sp"
        android:textStyle="bold" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#d7666666" />

</LinearLayout>

Full SourceCodeDownload

Live Sample

 







Saturday 8 October 2016

Pragmatically get SH1 code in android


Windows
Before going to console set your jre path your envoirmental system
Go to MyComputer and right click
1> Go to property
2>Go to advanced system setting
3>Tab "adavance"
4> Go to bottom "Envoirmental variables"
5>Now you create new or edit and paste your jre path

and now go to your  console

C:\Program Files\Java\jre7\bin>keytool -list -alias androiddebugkey -keystore "C:\Users\user\.android\debug.keystore" -storepass android -keypass android

Wednesday 5 October 2016

Date range picker in android



activity.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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.samset.user.calendersample.MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.TabLayout
            android:id="@+id/rentTabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            app:tabBackground="@color/white"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabSelectedTextColor="@color/colorAccent"
            app:tabTextAppearance="@style/CustomTabTextBold"
            app:tabTextColor="@color/line_light_grey" />
        <FrameLayout
            android:layout_weight="1"
            android:id="@+id/rent_tab"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
        <LinearLayout
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.AppCompatButton
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:id="@+id/btn_submit"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:background="@color/colorAccent"
                android:text="Submit"
                android:textColor="#FFFFFF" />

        </LinearLayout>

    </LinearLayout>


</RelativeLayout>


MainActivity.java


package com.samset.user.calendersample;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.samset.user.calendersample.fragment.TabFromFragment;
import com.samset.user.calendersample.fragment.TabToFragment;
import com.samset.user.calendersample.views.CalendarView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;


public class MainActivity extends AppCompatActivity {
    CalendarView simpleCalendarView;

    TabLayout tabLayout;

    TabLayout.Tab tabFrom;
    TabLayout.Tab tabTo;

    String from,to;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout) findViewById(R.id.rentTabLayout);
        findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (from!=null)
                {
                    if (to!=null)
                    {
                        Toast.makeText(MainActivity.this,"From "+from+" To "+to,Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(MainActivity.this,"Select from date",Toast.LENGTH_SHORT).show();
                }
            }
        });
        setTab();


    }

    private void setTab() {

        tabFrom = tabLayout.newTab();
        tabFrom.setText("FROM");
        //tabOffers.setIcon(R.drawable.ic_home);
        tabLayout.addTab(tabFrom);
        beginTransction(new TabFromFragment());

        tabTo = tabLayout.newTab();
        tabTo.setText("TO");
        tabLayout.addTab(tabTo);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Fragment fragment = null;
                switch (tab.getPosition()) {
                    case 0:
                        fragment = new TabFromFragment();
                        break;
                    case 1:
                        fragment = new TabToFragment();
                        break;

                }
                beginTransction(fragment);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void getSelectedDatefrom(String data)
    {
        this.from=data;
    }
    public void getSelectedDateto(String data)
    {
       this.to=data;
    }



    private void beginTransction(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.rent_tab, fragment);
        //transaction.addToBackStack(null);
        transaction.commit();

    }
}


TabFromFragment.java

package com.samset.user.calendersample.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import com.samset.user.calendersample.MainActivity;
import com.samset.user.calendersample.R;
import com.samset.user.calendersample.views.CalendarView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

/**
 * A simple {@link Fragment} subclass.
 */
public class TabFromFragment extends Fragment {
    private View view;
    private CalendarView calendarView;

    public TabFromFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tab_from, container, false);
        initView(view);

        return view;
    }

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

    }

    private void getSelectedDate()
    {
        HashSet<Date> events = new HashSet<>();
        events.add(new Date());

        calendarView.updateCalendar(events);

        calendarView.setEventHandler(new CalendarView.EventHandler()
        {
            @Override
            public void onDayLongPress(Date date)
            {
                // show returned day
                DateFormat df = SimpleDateFormat.getDateInstance();
                Toast.makeText(getActivity(), df.format(date), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemClick(Date date) {
                DateFormat df = SimpleDateFormat.getDateInstance();
                ((MainActivity)getActivity()).getSelectedDatefrom(df.format(date));
                Toast.makeText(getActivity(), df.format(date), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initView(View view) {
        calendarView = (CalendarView) view.findViewById(R.id.calendar_view);
    }

}

Thank you 
Live Sample
FullSource codeDateRanger





Tuesday 4 October 2016

BottomSheetDialogsample in android



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purpule_light"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <Button
            android:id="@+id/btnDialog"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show dialog" />
    </LinearLayout>

</LinearLayout>


MainActivity,java

package com.samset.user.bottomsheetsample;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {

    private Button btnDialog;
    private BottomSheetDialog bottomSheetDialog;


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

        btnDialog = (Button) findViewById(R.id.btnDialog);
        btnDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetDialog();
            }
        });

    }
    private void showBottomSheetDialog() {

        bottomSheetDialog = new BottomSheetDialog(this);
        View view = getLayoutInflater().inflate(R.layout.bottomsheet, null);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.rg_sortby);

        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.show();
        bottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // collapse(bottomSheetDialog);
                bottomSheetDialog = null;
            }
        });
    }


}

bottomsheet.xml


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


    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_horizontal_margin"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_marginTop="10dp"
            android:text="Sort by"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <View
            android:layout_marginTop="5dp"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#e5e5e5"/>

        <RadioGroup
            android:id="@+id/rg_sortby"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:gravity="center">

            <RadioButton
                android:text="@string/popularity"
                android:gravity="right|center_vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />


            <RadioButton
                android:text="@string/new_arrivals"
                android:gravity="right|center_vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <RadioButton
                android:gravity="right|center_vertical"
                android:text="@string/price_low_to_high"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <RadioButton
                android:gravity="right|center_vertical"
                android:text="@string/price_hight_to_low"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </RadioGroup>
    </LinearLayout>
</LinearLayout>


Thank you

Live Sample















Friday 30 September 2016

Transparent dialogbox in android





private void showDialogBox() {


    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = LayoutInflater.from(getActivity());


    View view = inflater.inflate(R.layout.dialog_logout, null);
    dialogBuilder.setCancelable(false);


    TextViewMedium logout = (TextViewMedium) view.findViewById(R.id.tvm_logout);


    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getActivity(), SplashActivity.class));
            dialog.dismiss();
        }
    });
    dialogBuilder.setView(view);

    dialog = dialogBuilder.create();

//Make transparent your dialogbox background
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));


// Yoc can open dialogbox where you decide top,bottom,left,right.... 
    Window dialogWindow = dialog.getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    dialogWindow.setGravity(Gravity.CENTER | Gravity.CENTER);

    dialog.show();


}

Wednesday 14 September 2016

Fragment back handle in android

Hello friends

Today we are learn about fragment  methods most of developer can't handle proper fragment navigation so i found best solution and proper navigation of fragment.If you learn this post i am sure you feel relax with fragment navigation. So lets start.....

First you create a new android project.

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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.samset.user.fragmentbackprocesssample.MainActivity">

    <LinearLayout
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/primary_dark"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Fragment Navigation"
            android:textColor="#fff" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/mainContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tv"></FrameLayout>
</RelativeLayout>


MainActvity.java

package com.samset.user.fragmentbackprocesssample;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.samset.user.fragmentbackprocesssample.fragments.HomeFragment;
import com.samset.user.fragmentbackprocesssample.fragments.LoginFragment;

public class MainActivity extends AppCompatActivity {
    String TAG = MainActivity.class.getSimpleName();

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

    @Override
    protected void onResume() {
        super.onResume();

    }

    public void fragTransaction(Fragment frag) {
        if (frag.isAdded()) {
            Log.e(TAG, " fragment add");
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(R.id.mainContainer, frag).addToBackStack(null).commit();
        } else {
            Log.e(TAG, " fragment replace");
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.mainContainer, frag).addToBackStack(null).commit();
        }
    }


    @Override
    public void onBackPressed() {

        // here you simply back handle you check stack count and then enable backpress button
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStack();
            Log.e(TAG, " fragment popback ");
        } else {
            super.onBackPressed();
        }
    }
}


HomeFragment.java


package com.samset.user.fragmentbackprocesssample.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.samset.user.fragmentbackprocesssample.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    private AppCompatButton btnProfile,btnDetails;
    public HomeFragment() {
        // Required empty public constructor
    }


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

        btnProfile= (AppCompatButton) view.findViewById(R.id.btnprofile);
        btnDetails= (AppCompatButton) view.findViewById(R.id.btndetails);


        return view;
    }

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

        btnProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction=manager.beginTransaction();    //If you add tag name the you can navigate anywhere from any frgament
                transaction.replace(R.id.mainContainer,new ProfileFragment()).addToBackStack("home").commit();
            }
        });
        btnDetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getFragmentManager();
                FragmentTransaction transaction=manager.beginTransaction();    //If you add tag name the you can navigate anywhere from any frgament
                transaction.replace(R.id.mainContainer,new DetailsFragment()).addToBackStack("home").commit();
            }
        });
    }
}


Thank you

FullSourceCodeFragmentPopBackStack

Live Sample









Tuesday 13 September 2016

AppIntro in android

Hi friends

If you want add app intro in your app then you use this sample and make your app more beautiful.

Create a new android project and follow some instructions ....

activity_main.xml

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

ActvityMain.java

package com.samset.user.appintro;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.samset.user.appintro.adapters.MyPagerAdapter;
import com.samset.user.appintro.transformations.IntroPageTransformer;
import com.samset.user.appintro.transformations.ZoomOutPageTransformer;

public class MainActivity extends AppCompatActivity {
    private ViewPager pager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pager = (ViewPager) findViewById(R.id.viewpager);
        // Set an Adapter on the ViewPager
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        pager.setPageTransformer(false, new IntroPageTransformer());
    }


}


Pageradapter.java


package com.samset.user.appintro.adapters;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.samset.user.appintro.fragments.FirstFragment;

/**
 * Created by user on 13-Sep-16.
 */
public class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return FirstFragment.newInstance(Color.parseColor("#03A9F4"), position); // blue
            case 1:
                return FirstFragment.newInstance(Color.parseColor("#9C27B0"), position); // purpal
            case 2:
                return FirstFragment.newInstance(Color.parseColor("#E91E63"), position); // pink
            case 3:
                return FirstFragment.newInstance(Color.parseColor("#F44336"), position); // red
            default:
                return FirstFragment.newInstance(Color.parseColor("#4CAF50"), position); // green
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

}

Thank you
 Fullsource codeAppIntro

Live Sample






ViewPager transformation in android

Hi friends
Today we are learn about how to animate view pager pages so lets start and make your app more beautiful.

Create a new android project and follow some instructions ....

activity_main.xml

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

ActvityMain.java

package com.samset.user.appintro;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.samset.user.appintro.adapters.MyPagerAdapter;
import com.samset.user.appintro.transformations.IntroPageTransformer;
import com.samset.user.appintro.transformations.ZoomOutPageTransformer;

public class MainActivity extends AppCompatActivity {
    private ViewPager pager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pager = (ViewPager) findViewById(R.id.viewpager);
        // Set an Adapter on the ViewPager
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        // Set a PageTransformer
        // pager.setPageTransformer(false, new IntroPageTransformer());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.trans_1:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View page, float position) {
                        final float normalizedposition = Math.abs(Math.abs(position) - 1);
                        page.setAlpha(normalizedposition);
                    }
                });
                return true;
            case R.id.trans_2:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View page, float position) {
                        final float normalizedposition = Math.abs(Math.abs(position) - 1);
                        page.setScaleX(normalizedposition / 2 + 0.5f);
                        page.setScaleY(normalizedposition / 2 + 0.5f);
                    }
                });
                return true;
            case R.id.trans_3:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View page, float position) {
                        final float normalizedposition = Math.abs(Math.abs(position) - 1);
                        page.setScaleX(normalizedposition / 2 + 0.5f);
                        page.setScaleY(normalizedposition / 2 + 0.5f);
                    }
                });
                return true;
            case R.id.trans_4:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View page, float position) {
                        page.setRotationY(position * -30);
                    }
                });
                return true;
            case R.id.trans_5:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View view, float position) {
                        view.setTranslationX(view.getWidth() * -position);
                        if (position <= -1.0F || position >= 1.0F) {
                            view.setAlpha(0.0F);
                        } else if (position == 0.0F) {
                            view.setAlpha(1.0F);
                        } else {
                            // position is between -1.0F & 0.0F OR 0.0F & 1.0F
                            view.setAlpha(1.0F - Math.abs(position));
                        }

                    }
                });
                return true;
            case R.id.trans_6:
                pager.setPageTransformer(false, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View view, float position) {
                        view.setTranslationX(view.getWidth() * -position);

                        if (position <= -1.0F || position >= 1.0F) {        // [-Infinity,-1) OR (1,+Infinity]
                            view.setAlpha(0.0F);
                            view.setVisibility(View.GONE);
                        } else if( position == 0.0F ) {     // [0]
                            view.setAlpha(1.0F);
                            view.setVisibility(View.VISIBLE);
                        } else {

                            // Position is between [-1,1]
                            view.setAlpha(1.0F - Math.abs(position));
                            view.setTranslationX(-position * (view.getWidth() / 2));
                            view.setVisibility(View.VISIBLE);
                        }

                    }
                });
                return true;
            case R.id.trans_7:
                pager.setPageTransformer(false, new ZoomOutPageTransformer());
                return true;
            case R.id.trans_8:
                pager.setPageTransformer(false, new IntroPageTransformer());
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


Pageradapter.java


package com.samset.user.appintro.adapters;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.samset.user.appintro.fragments.FirstFragment;

/**
 * Created by user on 13-Sep-16.
 */
public class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return FirstFragment.newInstance(Color.parseColor("#03A9F4"), position); // blue
            case 1:
                return FirstFragment.newInstance(Color.parseColor("#9C27B0"), position); // purpal
            case 2:
                return FirstFragment.newInstance(Color.parseColor("#E91E63"), position); // pink
            case 3:
                return FirstFragment.newInstance(Color.parseColor("#F44336"), position); // red
            default:
                return FirstFragment.newInstance(Color.parseColor("#4CAF50"), position); // green
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

}

Thank you
 Fullsource codeViewPager_Transformation

Live Sample






Tuesday 6 September 2016

Dynamically change layout background color in android

Hi friends

If you want change your component background smoothly then follow below code

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:id="@+id/lin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.samset.user.customtoastsample.Test2">

<LinearLayout
    android:id="@+id/lay1"
    android:layout_width="200dp"
    android:layout_height="150dp">

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/pause"
        android:text="Pause"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

</LinearLayout>
   
</LinearLayout>


MainActivity.java

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.samset.user.customtoastsample.adapters.TopWinnerstest;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Test2 extends AppCompatActivity {
   
    LinearLayout lay1;
   

    int i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test2);
        lay1 = (LinearLayout) findViewById(R.id.lay1);
       


        ArgbEvaluator evaluator = new ArgbEvaluator();
        ValueAnimator animator = new ValueAnimator();
        animator.setIntValues(Color.parseColor("#78CC2E"),Color.parseColor("#901B8E"),      Color.parseColor("#e50000"),Color.parseColor("#FFC807"));
        animator.setEvaluator(evaluator);
        animator.setDuration(6000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.INFINITE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int  color1 = (int) animation.getAnimatedValue();
                //postInvalidate(); if you are animating a canvas
                lay1.setBackgroundColor(color1); //another exampleof where to use

            }
        });
        animator.start();

    }
}

Thanks

Live Sample





Pragmatically create gradient in android

Hello friends


actvity_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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.samset.user.dynamicallychangegradiant.MainActivity">


    <LinearLayout
        android:id="@+id/mainlayout"
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <TextView
            android:layout_gravity="center"
            android:gravity="center"
            android:textColor="#fff"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="samset.blogspot.com!" />

    </LinearLayout>
</RelativeLayout>


MainActivity.java

package com.samset.user.dynamicallychangegradiant;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
   private LinearLayout linearLayout;
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout= (LinearLayout) findViewById(R.id.mainlayout);

        final GradientDrawable[] colors = new GradientDrawable[]{getgradiantInit(), getgradiantFirst(), getgradiantSecond(), getgradiantThird()};

        new CountDownTimer(2000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                linearLayout.setBackground((colors[i]));
                i++;
                if (i == colors.length - 1) i = 0;
                start();
            }
        }.start();
    }


    public GradientDrawable getgradiantInit() {
        int[] colors = {Color.parseColor("#008000"), Color.parseColor("#ADFF2F")};
        GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
        gd.setCornerRadius(20f);
        return gd;
    }

    private GradientDrawable getgradiantFirst() {
        int[] colors1 = {Color.parseColor("#78CC2E"), Color.parseColor("#901B8E")};
        GradientDrawable gd1 = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors1);
        gd1.setCornerRadius(20f);

        return gd1;
    }

    private GradientDrawable getgradiantSecond() {
        int[] colors1 = {Color.parseColor("#e50000"), Color.parseColor("#FFC807")};
        GradientDrawable gd1 = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors1);
        gd1.setCornerRadius(20f);

        return gd1;
    }

    private GradientDrawable getgradiantThird() {
        int[] colors1 = {Color.parseColor("#3eb0f7"), Color.parseColor("#FFFFFF")};
        GradientDrawable gd1 = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors1);
        gd1.setCornerRadius(10f);

        return gd1;
    }
}


Thanks

Live Sample




Saturday 13 August 2016

Glide Image loader Library in android


Hello friends,

In this article explains how to build a simple image in app where the image will be loaded from internet. Glide is new image loading library and not only one lib the many other lib use the image loading like Picasso.

What is Picasso ?

Picasso is an image library for Android. It's created and maintained by Square, and caters to image loading and processing. It simplifies the process of displaying images from external locations. In many cases only a few lines of code is required to implement this neat library.

Picasso shines for displaying remote images. The library handles every stage of the process, from the initial HTTP request to the caching of the image. This can be quite verbose when writing code to perform these actions yourself. In this quick tip, we look at a few common use cases.

Picasso features :

1> Thumbnail support
2> Lifecycle integration
3> Transcoding
4> OkHttp Support
5> Volley Support


Why use glide:

You might be thinking that why we should use a 3rd party library. You can achieve your task without using a 3rd party API as well. I have also posted a tutorial about downloading image without using 3rd party library. But if you will use the core method then it would take larger amount of code. But if we will use a 3rd party library like picasso then we will achieve our goal in few lines of code.  So if we will not use a 3rd party library then  we would need

1> Very large amount of code to be written
2> We have to write another logic to implement caching. Caching is very important to make the application faster.
3> We also have to deal with memory while writing the code.
BUT if we will use picasso then all the above mentioned things would be taken care of by picasso.


What is Glide?

Glide is an open source media management framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface. Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. Glide includes a flexible API that allows developers to plug in to almost any network stack.

Glide’s primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.


Glide features :

1> Animated GIF decoding
2> Local video stills
3> Thumbnail support
4> Lifecycle integration
5> Transcoding
6> Animations
7> OkHttp Support
8> Volley Support

Why use glide:

It simplifies the process of loading images from external urls and display on your application. For example, downloading an image from server, is one of the most common task in any application. And it needs quite a larger amount of code to achieve this via android networking API’s. By using Glide, you can achieve this with few lines of code.

                                                                  It is always not about downloading image from remote location. You also have to think of implementing image caching logic in order to provide a seamless user experience. Glide provides automatic image caching.

                                                                  Image transformation is a costly affair. If your application need deal with such runtime image transformation, you must be watchful about OutOfMemoryException. Glide deals with it, so you dont have to do it yourself.


How to use?

Before you can use it in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file.


dependencies {
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.android.support:support-v4:19.1.0'
  }

MainActvity.java

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.GlideModule;
import com.samset.user.volleyexample.R;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    String imgUrl = "http://yourapiurl/sample.jpg";

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

        imageView = (ImageView) findViewById(R.id.img);
        Glide.with(this).load(imgUrl)
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);

//You can set manually DecodeFormat.PREFER_ARGB_8888 by default set RGB565
  /*Glide.with(this).load(imgUrl).asBitmap().format(DecodeFormat.PREFER_ARGB_8888)
                .thumbnail(0.5f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".activities.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="Welcome to glide tutorial" />
    <ImageView
        android:layout_marginTop="10dp"
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Also use methods

     Loading Images from server

   ImageView imageView = (ImageView) findViewById(R.id.imageView);

  //Loading image from below url into imageView
        Glide.with(this).load("IMAGE URL HERE").into(imageView);


    Set Images placeholder

   ImageView imageView = (ImageView) findViewById(R.id.imageView);


      Glide.with(this)
        .load("IMAGE URL HERE")
        .placeholder(R.drawable.placeholder)
        .into(imageView);


    Set Images error

   ImageView imageView = (ImageView) findViewById(R.id.imageView);

  Glide.with(this)
        .load("IMAGE URL HERE")
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.imagenotfound)
        .into(imageView);

    Image Resizing and Cropping

   ImageView imageView = (ImageView) findViewById(R.id.imageView);

  Glide.with(this)
        .load("IMAGE URL HERE")
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.imagenotfound)
        .into(imageView);


If you develop very large app and use max images then you face MemoryOutOfBound exception then you can customise as your need cache memory.

Cache

We're customizing Glide, we'll need to create a new Glide module. As you've seen in the previous blog post, the applyOptions method gives us access to the GlideBuilder object. The GlideBuilder offers us several methods to customize Glide's caching. First, let's look at the memory cache.

The memory cache keeps the images in the device's RAM. There is no IO action going on and thus it's very fast. The flip side is that the size of the RAM is quite limited. Finding the right balance of keeping a large memory cache (space for many images) versus a small memory cache (minimize our app's hunger for resources) is not easy. Glide internally uses the MemorySizeCalculator class to determine the size of the memory cache and the bitmap pool. The bitmap pool keeps the images allocated in your app's heap. The correct size of the bitmap pool is essential as well, since it avoids too many re-allocations of images and thus makes the garbage collector's life easier.

Luckily, you've access to Glide's MemorySizeCalculator class and the default calculation:



MemorySizeCalculator calculator = new MemorySizeCalculator(context);  
int defaultMemoryCacheSize = calculator.getMemoryCacheSize();  
int defaultBitmapPoolSize = calculator.getBitmapPoolSize();  

The code above is useful if we want to use the default values as baseline and adjust it from there. For example, if you think your app needs 20% larger caches than Glide's default values, calculate them using our variables above:

int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);  
int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize); 


Since we've figured out our memory cache and bitmap pool sizes, we can finally get to code our Glide module. In the applyOptions() method, we can call the appropriate methods on the GlideBuilder object:


public class CustomCachingGlideModule implements GlideModule {  
    @Override public void applyOptions(Context context, GlideBuilder builder) {
        MemorySizeCalculator calculator = new MemorySizeCalculator(context);
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
        int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

        builder.setMemoryCache( new LruResourceCache( customMemoryCacheSize );
        builder.setBitmapPool( new LruBitmapPool( customBitmapPoolSize );
    }

    @Override public void registerComponents(Context context, Glide glide) {
        // nothing to do here
    }
}

As you can see from the last two lines in the applyOptions() method, we can't set the size directly. We're creating an instance of the LruResourceCache and the LruBitmapPool class. Both are the default implementations of Glide. Thus, if you only want to adjust the size, you can just continue to use them by just passing a different size value to the constructor.

Customize Disk Cache

Adjusting the size of the disk cache works very similar, but we've one decision more to make. The disk cache can be located in the apps private directory (in other words, no app has access to it, except your own). Otherwise, the disk cache can also be located on the external, public directory (for more information, see Storage Options. A combination of both locations is not possible with the default settings. Glide offers an implementation for either one of the two options with the InternalCacheDiskCacheFactory and ExternalCacheDiskCacheFactory. Just like the memory cache constructor, both disk cache factories accept a size value in their constructor:


public class CustomCachingGlideModule implements GlideModule {  
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // set size & external vs. internal
        int cacheSize100MegaBytes = 104857600;

        builder.setDiskCache(
            new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)
        );

        //builder.setDiskCache(
        //new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        // nothing to do here
    }
}

The code above would set the disk cache to the app's internal directory and also set the maximum size to 100 megabytes. The line, which is behind the comment slashes, would set the disk cache to the external directory (and also set the maximum size to 100 megabytes).

Both options you've seen above don't let you choose a specific directory. If you require to move the disk cache to some specific location, you can utilize the DiskLruCacheFactory:


// or any other path
String downloadDirectoryPath = Environment.getDownloadCacheDirectory().getPath(); 

builder.setDiskCache(  
        new DiskLruCacheFactory( downloadDirectoryPath, cacheSize100MegaBytes )
);

// In case you want to specify a cache sub folder (i.e. "glidecache"):
//builder.setDiskCache(
//    new DiskLruCacheFactory( downloadDirectoryPath, "glidecache", cacheSize100MegaBytes ) 
//);


Use the upper option to set a directory directly. The bottom option would create and use a directory inside your passed directory path. As always, the last parameter is the size of the cache in bytes.



CompleteCode

      MainActivity.java


import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.GlideModule;
import com.samset.user.volleyexample.R;

public class MainActivity extends AppCompatActivity implements GlideModule {

    private ImageView imageView;
    String imgUrl = "http://yourapiurl/sample.jpg";

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

        imageView = (ImageView) findViewById(R.id.img);
        Glide.with(this).load(imgUrl)
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // add this code your picture quality good
        builder.setDecodeFormat(DecodeFormat.ALWAYS_ARGB_8888);



        int cacheSize100MegaBytes = 104857600;
        // This is maintain diskcache internal memory
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
        // This is maintain diskcache external memory
        builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));

        //If you require to move the disk cache to some specific location, you can utilize the DiskLruCacheFactory:
        String downloadDirectoryPath = Environment.getDownloadCacheDirectory().getPath();
        builder.setDiskCache(new DiskLruCacheFactory( downloadDirectoryPath, cacheSize100MegaBytes ));

    }

    @Override
    public void registerComponents(Context context, Glide glide) {
       // glide.register(Model.class, Data.class, new MyModelLoader());
    }
}


AndroidMainifest.xml


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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <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.inthecheesefactory.lab.glidepicasso.GlideConfiguration"
            android:value="GlideModule"/>

        <activity android:name=".activities.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Thank you