Showing posts with label Android Control. Show all posts
Showing posts with label Android Control. Show all posts

Tuesday, 2 April 2013

How to use preferences in android

From Developer.android.com: “android.preference package provides classes that manage application preferences and implement the preferences UI. Using these ensures that all the preferences within each application are maintained in the same manner and the user experience is consistent with that of the system and other applications.
The preferences portion of an application should be ran as a separate Activity that extends the PreferenceActivity class. In the PreferenceActivity, a PreferenceScreen object should be the root element of the layout. The PreferenceScreen contains Preference elements such as a CheckBoxPreference, EditTextPreference, ListPreference, PreferenceCategory, or RingtonePreference..."


In this tutorial we want to introduce you how to use some preference elements with their tasks in a setting activity externs the PreferenceActivity class. Those are some simple tasks setting for backup data like the photo shows in below:


1. Create layout file for preference settings
To make the setting interface we create a preference.xml file in folder res/layout/xml. All xml code to make that show below:

<?xml version="1.0"encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">  
   
                    <!-- 1 -->
                        <PreferenceCategory
                            android:key="category_location_backup"
                            android:title="Store Backup Settings"
                                android:layout="@layout/textlayout" >
                                <CheckBoxPreference
                                android:key="checkboxpref_location_backup"
                                android:title="Store at default location"
                                android:summaryOff="Check to enable choose location backup"
                                android:summaryOn="Check to disable choose location backup"   
                            />
                            <Preference android:key="pref_folder_chosen"
                                                    android:name="default_browser"
                                                    android:summary="Choose a folder on SDCard to store backup file"                                         
                                                    android:title="Choose location backup"                                     
                                />
                        </PreferenceCategory>
                       
                    <!-- 2 -->
                        <PreferenceCategory
                            android:title="Auto Backup Settings"
                            android:layout="@layout/textlayout">
                            <CheckBoxPreference android:key="checkboxpref_auto_backup"
                                android:title="Enable Auto Backup Settings"
                                android:summaryOff="Check to enable automatic backup in device"
                                android:summaryOn="Check to disable automatic backup in device" />
                            <PreferenceScreen android:title="Auto Backup Settings"
                                android:summary="Setting Date and Time for automatic backup"
                                android:dependency="checkboxpref_auto_backup">
                                    <PreferenceCategory android:title="SMS BACKUP SCHEDULE"
                                        android:layout="@layout/textlayout">
                                            <duytan.edu.vn.backupdemo.TimePreferenceCustom
                                                android:key="timepref_auto_backup"
                                                android:name="Default notification time"
                                                android:summary="Choose the time to automatic backup SMS"
                                                android:dialogLayout="@layout/time_preference"
                                                android:title="Time to auto backup SMS"
                                                android:layout="@layout/mylayout"/>
                                            <duytan.edu.vn.backupdemo.ListPreferenceMultiSelect
                                                android:key="daypref_auto_backup"
                                                android:selectable="true"
                                                android:dialogTitle="Day in week dialog"
                                                android:summary="Choose the date to automatic backup SMS"
                                                android:title="Day to auto backup SMS"
                                                android:entryValues="@array/array_multi_list_preference_entry_values"
                                                android:entries="@array/array_multi_list_preference_entries"
                                                android:layout="@layout/mylayout"/>
                                         </PreferenceCategory>
                           </PreferenceScreen>
                          
                        </PreferenceCategory>
                       
                    <!-- 3 -->
                    <PreferenceCategory
                                android:title="Restore Settings"
                                android:layout="@layout/textlayout">
                            <ListPreference
                                android:key="listpref_restore"
                                android:title="Restore Type"
                                android:summary="Choose the Type of restore."
                                android:entries="@array/array_list_preference_entries"
                                android:entryValues="@array/array_list_preference_entry_values"    
                                android:defaultValue="Keep current contains"   
                                />
                    </PreferenceCategory>
                    <!-- 4 -->
                    <PreferenceCategory
                                android:title="Other Settings"
                            android:layout="@layout/textlayout">
                            <Preference android:key="backup_setting_file"
                                            android:name="backup_setting_file"
                                            android:summary="Choose to backup all settings to file"                                          
                                            android:title="Backup all settings"                                        
                                />
                        </PreferenceCategory>
                     
</PreferenceScreen>

2. Demo with all preferences element.
2.1. For the CheckBoxPreference element  with android:key="checkboxpref_location_backup". This check for enable or disable users to choose the location in sdcard of device to store their backup file.
When disable

and when enable


2.2. For the  Preference element with android:key="pref_folder_chosen".  When user click on this setting then the app run the File explorer for choose one directory to store the backup file

When the File Explorer show up, if you choose the DCIM folder and return with back button on device


You will get the new location like that:


2.3. The CheckBoxPreference with  android:key="checkboxpref_auto_backup" enable or disable autto backup.
If users enable auto bakup then they can choose the days and time for that.


and when user click on Auto Backup Settings, the new PreferenceScreen will show like that:

 Now the time for user to choose the days and time for auto backup.
2.4. choose the time with the custom time preference element duytan.edu.vn.backupdemo.TimePreferenceCustom
with key timepref_auto_backup. and you can get the string for the time backup.

2.5. By the same with Date backup

Here is some demo for how to use simple preference elements in android. All reference source codes are available here. I hope this help for someone had began with preference class in android. Thanks for look at my blog. If you get confused with my poor English, please put a comment

Thursday, 28 March 2013

How to create custom Date Time Picker in Android

By the original SDK, you can choose the time and date for your app by using DatePicker, TimePicker and Date - TimePickerDialog but there is nothing built into Android to choose Date and Time in the same time like such a DateTimePicker. In this tutorial, i try to create a custom DateTimePicker that user can choose both date and time at the same time.
Here is a result of this tutorial:



This project is developed in Eclipse 4.2.0.
1. Make application interface:
The main layout of this app demo is very simple layout. It have one edit test, one button. When user touch on the button the DateTimePicket will show for choose the date and time, the result will be show on edit text. Here is some xml code to make main layout:





<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" >
    <EditText android:id="@+id/edittext1"
        android:hint="date and time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/button1"
        android:maxLines="1"
        android:layout_alignParentLeft="true"
    />
    <Button android:id="@+id/button1"
        android:text="Choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:onClick="button_click"
    />
 </RelativeLayout>



To show the custom picker shown in picture above i created a dialog contains three buttons and a new custom view DateTimePicker. The xml file design for dialog is shown here:
   


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/DateTimeDialog" android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <DateTimePicker.DateTimePicker
                android:id="@+id/DateTimePicker" android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        <LinearLayout android:id="@+id/ControlButtons"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_below="@+id/DateTimePicker"
                android:padding="5dip">
                <Button android:id="@+id/SetDateTime" android:layout_width="0dip"
                        android:text="@android:string/ok" android:layout_weight="1"
                        android:layout_height="wrap_content"  />
                <Button android:id="@+id/ResetDateTime" android:layout_width="0dip"
                        android:text="Reset" android:layout_weight="1"
                        android:layout_height="wrap_content" />
                <Button android:id="@+id/CancelDialog" android:layout_width="0dip"
                        android:text="@android:string/cancel" android:layout_weight="1"
                        android:layout_height="wrap_content" />
        </LinearLayout>
</RelativeLayout>

Finally, we need to create an interface for new DateTimePicker view. It simply has only some button and edit text. Here is all following xml codes to do that. Of course, you can make it better than me.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true"
        android:padding="5dip" android:id="@+id/DateTimePicker">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:baselineAligned="true"
    android:orientation="horizontal">
   
        <LinearLayout
        android:id="@+id/month_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:gravity="center"
        android:orientation="vertical" >
        <Button
            android:id="@+id/month_plus"
            android:layout_width="40dp"
            android:layout_height="28dp"    
            android:background="@drawable/image_button_up"/> 
        <EditText
            android:id="@+id/month_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:focusable="false"
            android:gravity="center"
            android:singleLine="true"
            android:textColor="#C0C0C0">
        </EditText>
        <Button
            android:id="@+id/month_minus"
            android:layout_width="40dp"
            android:layout_height="28dp"       
            android:background="@drawable/image_button_down"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/date_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:gravity="center"
        android:orientation="vertical" >
        <Button
            android:id="@+id/date_plus"
            android:layout_width="40dp"
            android:layout_height="28dp"       
            android:background="@drawable/image_button_up" />
        <EditText
            android:id="@+id/date_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:inputType="number"
            android:textColor="#C0C0C0"
            android:singleLine="true"/>
        <Button
            android:id="@+id/date_minus"
            android:layout_width="40dp"
            android:layout_height="28dp"       
            android:background="@drawable/image_button_down"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/year_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:gravity="center"
        android:orientation="vertical" >
        <Button
            android:id="@+id/year_plus"
            android:layout_width="40dp"
            android:layout_height="28dp"       
                android:background="@drawable/image_button_up"/>
        <EditText
            android:id="@+id/year_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:inputType="number"
            android:textColor="#C0C0C0"
            android:singleLine="true"/>
        <Button
            android:id="@+id/year_minus"
            android:layout_width="40dp"
            android:layout_height="28dp"       
            android:background="@drawable/image_button_down" />
    </LinearLayout>
    <LinearLayout
            android:id="@+id/hour_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:gravity="center"
            android:orientation="vertical">
            <Button
                android:id="@+id/hour_plus"
                android:layout_width="40dp"
                android:layout_height="28dp"           
                android:background="@drawable/image_button_up"/>
            <EditText
                android:id="@+id/hour_display"
                android:layout_width="45dp"
                android:layout_height="35dp"
                android:background="@drawable/picker_middle"
                android:gravity="center"
                android:inputType="number"
                android:textColor="#C0C0C0"
                    android:singleLine="true" >
            </EditText>
            <Button
                android:id="@+id/hour_minus"
                android:layout_width="40dp"
                android:layout_height="28dp"       
                android:background="@drawable/image_button_down"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/min_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:gravity="center"
            android:orientation="vertical">
            <Button
                android:id="@+id/min_plus"
                android:layout_width="40dp"
                android:layout_height="28dp"       
                android:background="@drawable/image_button_up"/>
            <EditText
                android:id="@+id/min_display"
                android:layout_width="45dp"
                android:layout_height="35dp"
                android:background="@drawable/picker_middle"
                android:gravity="center"
                android:inputType="number"
                android:textColor="#C0C0C0"
                android:singleLine="true"/>
            <Button
                android:id="@+id/min_minus"
                android:layout_width="40dp"
                android:layout_height="28dp"       
                android:background="@drawable/image_button_down"/>
        </LinearLayout>
</LinearLayout>
</RelativeLayout>


2. Time for java code:

The following code below implement when click on the button in main screen.

 public void button_click(View view){ 
        // Create the dialog
        final Dialog mDateTimeDialog = new Dialog(this);
        // Inflate the root layout
        final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
        // Grab widget instance
        final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
        mDateTimePicker.setDateChangedListener(this);
                 
        // Update demo edittext when the "OK" button is clicked
        ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
               mDateTimePicker.clearFocus();
               // TODO Auto-generated method stub
               String result_string = mDateTimePicker.getMonth() + "/" + String.valueOf(mDateTimePicker.getDay()) + "/" + String.valueOf(mDateTimePicker.getYear())
                                                + "  " + String.valueOf(mDateTimePicker.getHour()) + ":" + String.valueOf(mDateTimePicker.getMinute());
               edit_text.setText(result_string);
               mDateTimeDialog.dismiss();
         }
         });

         // Cancel the dialog when the "Cancel" button is clicked
         ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                     // TODO Auto-generated method stub
                     mDateTimeDialog.cancel();
                }
         });

                // Reset Date and Time pickers when the "Reset" button is clicked
       
         ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                      // TODO Auto-generated method stub
                      mDateTimePicker.reset();
                }
         });
                 
        // Setup TimePicker
        // No title on the dialog window
        mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Set the dialog content view
        mDateTimeDialog.setContentView(mDateTimeDialogView);
        // Display the dialog
        mDateTimeDialog.show();                
}

All we do in this function is create a new dialog, Inflate the root layout for that dialog then set OnClick Listener for three button in interface of dialog, finally we show diallog to the screen. When user click on one of three button, we must execute some task associate with each button. Exactly, cancel the dialog when the "Cancel" button is clicked, Reset Date and Time pickers when the "Reset" button is clicked and Update demo edittext when the "OK" button is clicked. 
The most important thing is we declare a DateTimePicker object mDateTimePicker and use many methods are  defined in the java class file like reset(), getDay(), getMonth() etc. The source code of DateTimePicker class available here.

3. DEMO

3.1. Run application


3.2. After click on the Choose button


3.3. click "OK" button on DateTimePicker Dialog


Reference: http://datetimepicker.googlecode.com/svn/trunk/
                   and
                   https://github.com/luminousman/DatePicker

PS: May be i make a lot of English grammar mistakes when create this tutorial cause my low level of English. Sorry about that.