Wednesday, 31 January 2018

Select DateTime, Date and Time Dialog Android Example


Output : 



                             


Create DateTime.Class File

package com.datetimedialog.datetimedialog;

/**
* Created by JAINISH on 1/31/2018.
*/

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTime {

   public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
   private Date mDate;
   private Calendar mCalendar;

   /**
    * Constructor with no parameters which will create DateTime
    * Object with the current date and time
    */
   public DateTime() {
       this(new Date());
   }

   /**
    * Constructor with Date parameter which will initialize the
    * object to the date specified
    * @param date
    */
   public DateTime(Date date) {
       mDate = date;
       mCalendar = Calendar.getInstance();
       mCalendar.setTime(mDate);
   }

   /**
    * Constructor with DateFormat and DateString which will be
    * used to initialize the object to the date string specified
    * @param dateFormat String DateFormat
    * @param dateString Date in String
    */
   public DateTime(String dateFormat, String dateString) {
       mCalendar = Calendar.getInstance();
       SimpleDateFormat mFormat = new SimpleDateFormat(dateFormat);
       try {
           mDate = mFormat.parse(dateString);
           mCalendar.setTime(mDate);
       } catch (ParseException e) {
           e.printStackTrace();
       }
   }

   /**
    * Constructor with DateString formatted as default DateFormat
    * defined in DATE_FORMAT variable
    * @param dateString
    */
   public DateTime(String dateString) {
       this(DATE_FORMAT, dateString);
   }

   /**
    * Constructor with Year, Month, Day, Hour, Minute, and Second
    * which will be use to set the date to
    * @param year Year
    * @param monthOfYear Month of Year
    * @param dayOfMonth Day of Month
    * @param hourOfDay Hour of Day
    * @param minuteOfHour Minute
    * @param secondOfMinute Second
    */
   public DateTime(int year, int monthOfYear, int dayOfMonth,
                   int hourOfDay, int minuteOfHour, int secondOfMinute) {
       mCalendar = Calendar.getInstance();
       mCalendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute);
       mDate = mCalendar.getTime();
   }

   /**
    * Constructor with Year, Month Day, Hour, Minute which
    * will be use to set the date to
    * @param year Year
    * @param monthOfYear Month of Year
    * @param dayOfMonth Day of Month
    * @param hourOfDay Hour of Day
    * @param minuteOfHour Minute
    */
   public DateTime(int year, int monthOfYear, int dayOfMonth,
                   int hourOfDay, int minuteOfHour) {
       this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0);
   }

   /**
    * Constructor with Date only (no time)
    * @param year Year
    * @param monthOfYear Month of Year
    * @param dayOfMonth Day of Month
    */
   public DateTime(int year, int monthOfYear, int dayOfMonth) {
       this(year, monthOfYear, dayOfMonth, 0,0,0);
   }

   public Date getDate() {
       return mDate;
   }

   public Calendar getCalendar() {
       return mCalendar;
   }

   public String getDateString(String dateFormat) {
       SimpleDateFormat mFormat = new SimpleDateFormat(dateFormat);
       return mFormat.format(mDate);
   }

   public String getDateString() {
       return getDateString(DATE_FORMAT);
   }

   public int getYear() {
       return mCalendar.get(Calendar.YEAR);
   }

   public int getMonthOfYear() {
       return mCalendar.get(Calendar.MONTH);
   }

   public int getDayOfMonth() {
       return mCalendar.get(Calendar.DAY_OF_MONTH);
   }

   public int getHourOfDay() {
       return mCalendar.get(Calendar.HOUR_OF_DAY);
   }

   public int getMinuteOfHour() {
       return mCalendar.get(Calendar.MINUTE);
   }

   public int getSecondOfMinute() {
       return mCalendar.get(Calendar.SECOND);
   }


}

Create DateTimePicker.class File

package com.datetimedialog.datetimedialog;

/**
* Created by JAINISH on 1/31/2018.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TimePicker;
import java.util.Date;

/**
* Created by Arman.Pagilagan on 15/05/14.
*/
public class DateTimePicker extends DialogFragment {
   public static final String TAG_FRAG_DATE_TIME = "fragDateTime";
   private static final String KEY_DIALOG_TITLE = "dialogTitle";
   private static final String KEY_INIT_DATE = "initDate";
   private static final String TAG_DATE = "date";
   private static final String TAG_TIME = "time";
   private Context mContext;
   private ButtonClickListener mButtonClickListener;
   private OnDateTimeSetListener mOnDateTimeSetListener;
   private Bundle mArgument;
   private DatePicker mDatePicker;
   private TimePicker mTimePicker;
   // DialogFragment constructor must be empty

   private boolean not_future = false;
   private String value_select = null;
   private LinearLayout date_content,time_content;

   public DateTimePicker() {
   }
   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);
       mContext = activity;
       mButtonClickListener = new ButtonClickListener();
   }
   /**
    *
    * @param dialogTitle Title of the DateTimePicker DialogFragment
    * @param initDate Initial Date and Time set to the Date and Time Picker
    * @return Instance of the DateTimePicker DialogFragment
    */
   public static DateTimePicker newInstance(CharSequence dialogTitle, Date initDate) {
       // Create a new instance of DateTimePicker
       DateTimePicker mDateTimePicker = new DateTimePicker();
       // Setup the constructor parameters as arguments
       Bundle mBundle = new Bundle();
       mBundle.putCharSequence(KEY_DIALOG_TITLE, dialogTitle);
       mBundle.putSerializable(KEY_INIT_DATE, initDate);
       mDateTimePicker.setArguments(mBundle);
       // Return instance with arguments
       return mDateTimePicker;
   }

   public static DateTimePicker newInstance(CharSequence dialogTitle, Date initDate, boolean not_future, String value_select) {
       // Create a new instance of DateTimePicker
       DateTimePicker mDateTimePicker = new DateTimePicker();
       // Setup the constructor parameters as arguments
       Bundle mBundle = new Bundle();
       mBundle.putCharSequence(KEY_DIALOG_TITLE, dialogTitle);
       mBundle.putSerializable(KEY_INIT_DATE, initDate);
       mDateTimePicker.setArguments(mBundle);

       mDateTimePicker.not_future = not_future;
       mDateTimePicker.value_select = value_select;

       // Return instance with arguments
       return mDateTimePicker;
   }
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
       // Retrieve Argument passed to the constructor
       mArgument = getArguments();
       // Use an AlertDialog Builder to initially create the Dialog
       AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext);
       // Setup the Dialog
       mBuilder.setTitle(mArgument.getCharSequence(KEY_DIALOG_TITLE));
       mBuilder.setNegativeButton(android.R.string.no,mButtonClickListener);
       mBuilder.setPositiveButton(android.R.string.yes,mButtonClickListener);
       // Create the Alert Dialog
       AlertDialog mDialog = mBuilder.create();
       // Set the View to the Dialog
       mDialog.setView(
               createDateTimeView(mDialog.getLayoutInflater())
       );
       // Return the Dialog created
       return mDialog;
   }
   /**
    * Inflates the XML Layout and setups the tabs
    * @param layoutInflater Layout inflater from the Dialog
    * @return Returns a view that will be set to the Dialog
    */
   private View createDateTimeView(LayoutInflater layoutInflater) {
       // Inflate the XML Layout using the inflater from the created Dialog
       View mView = layoutInflater.inflate(R.layout.date_time_picker,null);
       // Extract the TabHost
       TabHost mTabHost = (TabHost) mView.findViewById(R.id.tab_host);
       mTabHost.setup();
//        // Create Date Tab and add to TabHost
//        TabHost.TabSpec mDateTab = mTabHost.newTabSpec(TAG_DATE);
////        mDateTab.setIndicator(getString(R.string.tab_date));
//        mDateTab.setIndicator("Date");
//        mDateTab.setContent(R.id.date_content);
//        mTabHost.addTab(mDateTab);
//        // Create Time Tab and add to TabHost
//        TabHost.TabSpec mTimeTab = mTabHost.newTabSpec(TAG_TIME);
////        mTimeTab.setIndicator(getString(R.string.tab_time));
//        mTimeTab.setIndicator("Time");
//        mTimeTab.setContent(R.id.time_content);
//        mTabHost.addTab(mTimeTab);
       // Retrieve Date from Arguments sent to the Dialog
       DateTime mDateTime = new DateTime((Date) mArgument.getSerializable(KEY_INIT_DATE));
       // Initialize Date and Time Pickers
       mDatePicker = (DatePicker) mView.findViewById(R.id.date_picker);

       if (not_future){
           mDatePicker.setMaxDate(System.currentTimeMillis());
       }

       mTimePicker = (TimePicker) mView.findViewById(R.id.time_picker);
       mDatePicker.init(mDateTime.getYear(), mDateTime.getMonthOfYear(),
               mDateTime.getDayOfMonth(), null);
       mTimePicker.setCurrentHour(mDateTime.getHourOfDay());
       mTimePicker.setCurrentMinute(mDateTime.getMinuteOfHour());


       date_content = (LinearLayout) mView.findViewById(R.id.date_content);
       time_content = (LinearLayout) mView.findViewById(R.id.time_content);
       //value_select start
       if (value_select.equalsIgnoreCase(DateFormateclass.str_date_time)){
           // Create Date Tab and add to TabHost
           TabHost.TabSpec mDateTab = mTabHost.newTabSpec(TAG_DATE);
//        mDateTab.setIndicator(getString(R.string.tab_date));
           mDateTab.setIndicator("Date");
           mDateTab.setContent(R.id.date_content);
           mTabHost.addTab(mDateTab);
           // Create Time Tab and add to TabHost
           TabHost.TabSpec mTimeTab = mTabHost.newTabSpec(TAG_TIME);
//        mTimeTab.setIndicator(getString(R.string.tab_time));
           mTimeTab.setIndicator("Time");
           mTimeTab.setContent(R.id.time_content);
           mTabHost.addTab(mTimeTab);
       }else if (value_select.equalsIgnoreCase(DateFormateclass.str_date)){
           // Create Date Tab and add to TabHost
           TabHost.TabSpec mDateTab = mTabHost.newTabSpec(TAG_DATE);
//        mDateTab.setIndicator(getString(R.string.tab_date));
           mDateTab.setIndicator("Date");
           mDateTab.setContent(R.id.date_content);
           mTabHost.addTab(mDateTab);
           date_content.setVisibility(View.VISIBLE);
           time_content.setVisibility(View.GONE);
       }else if (value_select.equalsIgnoreCase(DateFormateclass.str_time)){
           // Create Time Tab and add to TabHost
           TabHost.TabSpec mTimeTab = mTabHost.newTabSpec(TAG_TIME);
//        mTimeTab.setIndicator(getString(R.string.tab_time));
           mTimeTab.setIndicator("Time");
           mTimeTab.setContent(R.id.time_content);
           mTabHost.addTab(mTimeTab);
           date_content.setVisibility(View.GONE);
           time_content.setVisibility(View.VISIBLE);
       }
       //value_select end


       // Return created view
       return mView;
   }
   /**
    * Sets the OnDateTimeSetListener interface
    * @param onDateTimeSetListener Interface that is used to send the Date and Time
    *               to the calling object
    */
   public void setOnDateTimeSetListener(OnDateTimeSetListener onDateTimeSetListener) {
       mOnDateTimeSetListener = onDateTimeSetListener;
   }
   private class ButtonClickListener implements DialogInterface.OnClickListener {
       @Override
       public void onClick(DialogInterface dialogInterface, int result) {
           // Determine if the user selected Ok
           if(DialogInterface.BUTTON_POSITIVE == result) {
               DateTime mDateTime = new DateTime(
                       mDatePicker.getYear(),
                       mDatePicker.getMonth(),
                       mDatePicker.getDayOfMonth(),
                       mTimePicker.getCurrentHour(),
                       mTimePicker.getCurrentMinute()
               );
               mOnDateTimeSetListener.DateTimeSet(mDateTime.getDate());
           }
       }
   }
   /**
    * Interface for sending the Date and Time to the calling object
    */
   public interface OnDateTimeSetListener {
       public void DateTimeSet(Date date);
   }
}


Create Activity MainActivity.class File 

package com.datetimedialog.datetimedialog;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.ParseException;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, DateTimePicker.OnDateTimeSetListener {

   TextView txt_datetime,txt_date,txt_time;
   Button btn_datetime,btn_date,btn_time;

   String str;

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

       txt_datetime = findViewById(R.id.txt_datetime);
       txt_date = findViewById(R.id.txt_date);
       txt_time = findViewById(R.id.txt_time);
       btn_datetime = findViewById(R.id.btn_datetime);
       btn_date = findViewById(R.id.btn_date);
       btn_time = findViewById(R.id.btn_time);

       btn_datetime.setOnClickListener(this);
       btn_date.setOnClickListener(this);
       btn_time.setOnClickListener(this);
   }

   @Override
   public void onClick(View view) {
       switch (view.getId()){
           case R.id.btn_datetime:
               str = DateFormateclass.str_date_time;
               getDateTime("");
               break;
           case R.id.btn_date:
               str = DateFormateclass.str_date;
               getDateTime("");
               break;
           case R.id.btn_time:
               str = DateFormateclass.str_time;
               getDateTime("");
               break;
       }
   }

   private void getDateTime(String str_date) {

       Date date1 = null;
       if (str_date != null && !str_date.equalsIgnoreCase("")){
           try {
               date1 = DateFormateclass.sdf_date.parse(str_date);
           } catch (ParseException e) {
               e.printStackTrace();
           }
       }else {
           date1 = new Date();
       }

       if (str.equalsIgnoreCase(DateFormateclass.str_date_time)){
           SimpleDateTimePicker simpleDateTimePicker = SimpleDateTimePicker.make(
                   DateFormateclass.str_date_time,
                   date1,
                   this,
                   getSupportFragmentManager()
           );
           // Show It baby!
           simpleDateTimePicker.show(false, DateFormateclass.str_date_time);
       }else if (str.equalsIgnoreCase(DateFormateclass.str_date)){
           SimpleDateTimePicker simpleDateTimePicker = SimpleDateTimePicker.make(
                   DateFormateclass.str_date,
                   date1,
                   this,
                   getSupportFragmentManager()
           );
           // Show It baby!
           simpleDateTimePicker.show(false, DateFormateclass.str_date);
       }else if (str.equalsIgnoreCase(DateFormateclass.str_time)){
           SimpleDateTimePicker simpleDateTimePicker = SimpleDateTimePicker.make(
                   DateFormateclass.str_time,
                   date1,
                   this,
                   getSupportFragmentManager()
           );
           // Show It baby!
           simpleDateTimePicker.show(false, DateFormateclass.str_time);
       }

   }

   @Override
   public void DateTimeSet(Date date) {
       DateTime mDateTime = new DateTime(date);
       if (str.equalsIgnoreCase(DateFormateclass.str_date_time)){
           txt_datetime.setText(DateFormateclass.sdf_date_time.format(date));
       }else if (str.equalsIgnoreCase(DateFormateclass.str_date)){
           txt_date.setText(DateFormateclass.sdf_date.format(date));
       }else if (str.equalsIgnoreCase(DateFormateclass.str_time)){
           txt_time.setText(DateFormateclass.sdf_time.format(date));
       }
   }
}

Create DateFormateclass.class File

package com.datetimedialog.datetimedialog;

/**
* Created by JAINISH on 1/31/2018.
*/

import java.text.SimpleDateFormat;

public class DateFormateclass {

   public final static SimpleDateFormat sdf_date_time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
   public final static SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");
   public final static SimpleDateFormat sdf_time = new SimpleDateFormat("HH:mm:ss");

   public final static String str_date_time ="Set Date & Time";
   public final static String str_date ="Set Date";
   public final static String str_time ="Set Time";
}


Create SimpleDateTimePicker.class File

package com.datetimedialog.datetimedialog;

/**
* Created by JAINISH on 1/31/2018.
*/

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.Date;

public class SimpleDateTimePicker {

   private CharSequence mDialogTitle;
   private Date mInitDate;
   private DateTimePicker.OnDateTimeSetListener mOnDateTimeSetListener;
   private FragmentManager mFragmentManager;

   /**
    * Private constructor that can only be access using the make method
    * @param dialogTitle Title of the Date Time Picker Dialog
    * @param initDate Date object to use to set the initial Date and Time
    * @param onDateTimeSetListener OnDateTimeSetListener interface
    * @param fragmentManager Fragment Manager from the activity
    */
   private SimpleDateTimePicker(CharSequence dialogTitle, Date initDate,
        DateTimePicker.OnDateTimeSetListener onDateTimeSetListener,
               FragmentManager fragmentManager) {

       // Find if there are any DialogFragments from the FragmentManager
       FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction();
       Fragment mDateTimeDialogFrag = fragmentManager.findFragmentByTag(
               DateTimePicker.TAG_FRAG_DATE_TIME
       );

       // Remove it if found
       if(mDateTimeDialogFrag != null) {
           mFragmentTransaction.remove(mDateTimeDialogFrag);
       }
       mFragmentTransaction.addToBackStack(null);

       mDialogTitle = dialogTitle;
       mInitDate = initDate;
       mOnDateTimeSetListener = onDateTimeSetListener;
       mFragmentManager = fragmentManager;

   }

   /**
    * Creates a new instance of the SimpleDateTimePicker
    * @param dialogTitle Title of the Date Time Picker Dialog
    * @param initDate Date object to use to set the initial Date and Time
    * @param onDateTimeSetListener OnDateTimeSetListener interface
    * @param fragmentManager Fragment Manager from the activity
    * @return Returns a SimpleDateTimePicker object
    */
   public static SimpleDateTimePicker make(CharSequence dialogTitle, Date initDate,
          DateTimePicker.OnDateTimeSetListeneronDateTimeSetListener,                                        FragmentManager fragmentManager) {

       return new SimpleDateTimePicker(dialogTitle, initDate,
               onDateTimeSetListener, fragmentManager);

   }

   /**
    * Shows the DateTimePicker Dialog
    */
   public void show() {

       // Create new DateTimePicker
       DateTimePicker mDateTimePicker = DateTimePicker.newInstance(mDialogTitle,mInitDate);
       mDateTimePicker.setOnDateTimeSetListener(mOnDateTimeSetListener);
       mDateTimePicker.show(mFragmentManager, DateTimePicker.TAG_FRAG_DATE_TIME);
   }

   public void show(boolean not_future, String value_select) {

       // Create new DateTimePicker
       DateTimePicker mDateTimePicker =                        DateTimePicker.newInstance(mDialogTitle,mInitDate,not_future,value_select);
       mDateTimePicker.setOnDateTimeSetListener(mOnDateTimeSetListener);
       mDateTimePicker.show(mFragmentManager, DateTimePicker.TAG_FRAG_DATE_TIME);
   }
}

Add 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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.datetimedialog.datetimedialog.MainActivity"
   android:orientation="vertical"
   android:padding="5dp"
   android:gravity="center">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal">
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="0.7"
           android:text="Date Time : "
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:id="@+id/txt_datetime"
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
   </LinearLayout>

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/btn_datetime"
       android:text="Date Time"/>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:layout_marginTop="20dp">
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="0.7"
           android:text="Date : "
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:id="@+id/txt_date"
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
   </LinearLayout>

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/btn_date"
       android:text="Date"/>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:layout_marginTop="20dp">
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="0.7"
           android:text="Time : "
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
       <TextView
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:id="@+id/txt_time"
           android:textStyle="bold"
           android:textSize="20dp"
           android:gravity="center"/>
   </LinearLayout>

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/btn_time"
       android:text="Time"/>

</LinearLayout>

Add date_time_picker.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/date_time"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">

   <!-- TabHost that will hold the Tabs and its content -->
   <TabHost
       android:id="@+id/tab_host"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

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

           <!-- TabWidget that will hold the Tabs -->
           <TabWidget
               android:id="@android:id/tabs"
               android:layout_width="match_parent"
               android:layout_height="match_parent" />

           <!-- Layout that will hold the content of the Tabs -->
           <FrameLayout
               android:id="@android:id/tabcontent"
               android:layout_width="match_parent"
               android:layout_height="match_parent">

               <!-- Layout for the DatePicker -->
               <LinearLayout
                   android:id="@+id/date_content"
                   android:orientation="vertical"
                   android:layout_width="match_parent"
                   android:layout_height="match_parent">

                   <DatePicker
                       android:id="@+id/date_picker"
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:calendarViewShown="false" />

               </LinearLayout>

               <!-- Layout for the TimePicker -->
               <LinearLayout
                   android:id="@+id/time_content"
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:orientation="vertical">

                   <TimePicker
                       android:id="@+id/time_picker"
                       android:layout_width="match_parent"
                       android:layout_height="match_parent" />

               </LinearLayout>

           </FrameLayout>

       </LinearLayout>

   </TabHost>

</LinearLayout>

Wednesday, 23 August 2017

DoubleSideDrawer Android Example

activity_main.xml


<?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"    
    xmlns:tools="http://schemas.android.com/tools"    
    android:id="@+id/drawer_layout"    
    android:layout_width="match_parent"     
    android:layout_height="match_parent"    
    android:fitsSystemWindows="true"    
    tools:openDrawer="start">

    <include        
      layout="@layout/app_bar_main"        
      android:layout_width="match_parent"        
      android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView        
       android:id="@+id/nav_view"        
       android:layout_width="wrap_content"         
       android:layout_height="match_parent"        
       android:layout_gravity="start"   
       android:fitsSystemWindows="true"  
       app:headerLayout="@layout/nav_header_main"   
       app:menu="@menu/activity_main_drawer" />

    <android.support.design.widget.NavigationView     
        android:id="@+id/nav_right_view"  
        android:layout_width="wrap_content"  
        android:layout_height="match_parent"    
        android:layout_gravity="end"  
        android:fitsSystemWindows="true"   
        app:headerLayout="@layout/nav_header_main"  
        app:menu="@menu/activity_right_drawer" />
    </android.support.v4.widget.DrawerLayout>




app_bar_main.xml
<?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"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.doublesidedrawerexample.MainActivity">

    <android.support.design.widget.AppBarLayout      
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar          
            android:id="@+id/toolbar"      
            android:layout_width="match_parent"  
            android:layout_height="?attr/actionBarSize"   
            android:background="?attr/colorPrimary"  
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>


content_main.xml
<?xml version="1.0" encoding="utf-8"?>
     <RelativeLayout 
              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/content_main"
              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"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"
              tools:context="com.doublesidedrawerexample.MainActivity"
              tools:showIn="@layout/app_bar_main">

    <TextView     
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content" 
        android:text="Hello World!" />
</RelativeLayout>


nav_header_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"
               android:layout_width="match_parent"
               android:layout_height="@dimen/nav_header_height"
               android:background="@drawable/side_nav_bar"
               android:gravity="bottom"
               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"
               android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@android:drawable/sym_def_app_icon" />

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>



activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
     <menu xmlns:android="http://schemas.android.com/apk/res/android">

      <group android:checkableBehavior="single">
        <item  
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item            
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>


activity_right_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item android:title="Account">
            <menu>
                <item
                    android:id="@+id/nav_settings"
                    android:icon="@drawable/ic_menu_share"
                    android:title="Settings" />
                <item
                    android:id="@+id/nav_logout"
                    android:icon="@drawable/ic_menu_send"
                    android:title="Logout" />
            </menu>
        </item>

        <item
            android:id="@+id/nav_help"
            android:icon="@drawable/ic_menu_camera"
            android:title="Help" />
        <item
            android:id="@+id/nav_about"
            android:icon="@drawable/ic_menu_gallery"
            android:title="About" />
    </group>

</menu>



main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_openRight"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        android:icon="@drawable/ic_menu_manage"
        app:showAsAction="always" />
</menu>


side_nav_bar.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="135"
        android:centerColor="#4CAF50"
        android:endColor="#2E7D32"
        android:startColor="#81C784"
        android:type="linear" />
</shape>

MainActivity.class
package com.doublesidedrawerexample;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView,rightNavigationView;
    DrawerLayout drawer;

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

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        rightNavigationView = (NavigationView) findViewById(R.id.nav_right_view);
        rightNavigationView.setNavigationItemSelectedListener(this);
    }

    @Override    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if (id == R.id.action_openRight) {
            drawer.openDrawer(GravityCompat.END);
        /*Opens the Right Drawer*/
            return true;
        }


        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.        
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action        
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        else if (id == R.id.nav_settings) {

        } else if (id == R.id.nav_logout) {

        } else if (id == R.id.nav_help) {

        } else if (id == R.id.nav_about) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


build.gradle
compile 'com.android.support:design:24.2.1'

Thursday, 20 April 2017

Android YouTube Integration Example


YouTube Integration





  • Create Application

First step in registering application is create a new application developer console. 
So, go to Google Developer Console. Create a new project, named YoutubeVideo.

  • Enable YouTube API

To use API, first you need to enable them in the dashboard.
So, click on the Enable and manage APIs.
This will redirect you to list of all the Google APIs. Here, click on the YouTube Data API to enable YouTube API for your project.

In the resulting screen, click on Enable button which will enable the API andwill ask you to create credentials for your application.



After enabling the API, you need to create the credentials to authenticate app. To create credentials,
click on Go To Credentials button in the dashboard.




This will redirect you to create Android Key form.





  • Download Library

First step in integrating YouTube Player API is downloading the YouTube Android Player API Library. Use YouTube Android Player API link to download the latest library and move it to app’s libs folder. Now, you need to add the library as application dependency. To do so, open app’s build.gradle file and add the below line as dependency :
androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support:support-annotations:25.2.0'

  • AndroidManjfest.xml

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

  • Activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.youtubevideo.MainActivity"> <com.google.android.youtube.player.YouTubePlayerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/youtube_player_view"> </com.google.android.youtube.player.YouTubePlayerView> </RelativeLayout>

  • MainActivity.java

package com.youtubevideo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { //AIzaSyB6dzPRjIZNe_OE6kJRes6370TV4vrTnL0 public static final String API_KEY = "AIzaSyB6dzPRjIZNe_OE6kJRes6370TV4vrTnL0"; //https://www.youtube.com/watch?v=<VIDEO_ID> public static final String VIDEO_ID = "3VxWcqo2sqs"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing YouTube player view YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view); youTubePlayerView.initialize(API_KEY, this); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if(null== player) return; // Start buffering if (!wasRestored) { player.cueVideo(VIDEO_ID); } // Add listeners to YouTubePlayer instance player.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() { @Override public void onAdStarted() { } @Override public void onError(YouTubePlayer.ErrorReason arg0) { } @Override public void onLoaded(String arg0) { } @Override public void onLoading() { } @Override public void onVideoEnded() { } @Override public void onVideoStarted() { } }); player.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() { @Override public void onBuffering(boolean arg0) { } @Override public void onPaused() { } @Override public void onPlaying() { } @Override public void onSeekTo(int arg0) { } @Override public void onStopped() { } }); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { Toast.makeText(this, "Failed to initialize.", Toast.LENGTH_LONG).show(); } }