Phonegap the use of custom widget (date picker)

Note: Article from: http://blog.163.com/da7_1@126/blog/static/104072678201292602950121/

DatePickerPlugin.java:

package org.apache.cordova;

import java.util.Calendar;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.TimePicker;

public class DatePickerPlugin extends Plugin {
	private static final String ACTION_DATE = "date";
	private static final String ACTION_TIME = "time";

	@Override
	public PluginResult execute(final String action, final JSONArray data,
			final String callBackId) {
		Log.d("DatePickerPlugin", "Plugin Called");
		PluginResult result = null;

		if (ACTION_DATE.equalsIgnoreCase(action)) {
			Log.d("DatePickerPluginListener execute", ACTION_DATE);
			this.showDatePicker(callBackId);
			final PluginResult r = new PluginResult(
					PluginResult.Status.NO_RESULT);
			r.setKeepCallback(true);
			return r;

		} else if (ACTION_TIME.equalsIgnoreCase(action)) {
			Log.d("DatePickerPluginListener execute", ACTION_TIME);
			this.showTimePicker(callBackId);
			final PluginResult r = new PluginResult(
					PluginResult.Status.NO_RESULT);
			r.setKeepCallback(true);
			return r;

		} else {
			result = new PluginResult(Status.INVALID_ACTION);
			Log.d("DatePickerPlugin", "Invalid action : " + action + " passed");
		}

		return result;
	}

	public synchronized void showTimePicker(final String callBackId) {
		final DatePickerPlugin datePickerPlugin = this;
		final Context currentCtx = cordova.getActivity();

		final Runnable runnable = new Runnable() {

			public void run() {
				final TimePickerDialog tpd = new TimePickerDialog(currentCtx,
						new OnTimeSetListener() {

							public void onTimeSet(final TimePicker view,
									final int hourOfDay, final int minute) {
								final JSONObject userChoice = new JSONObject();
								try {
									userChoice.put("hour", hourOfDay);
									userChoice.put("min", minute);
								} catch (final JSONException jsonEx) {
									Log.e("showDatePicker",
											"Got JSON Exception "
													+ jsonEx.getMessage());
									datePickerPlugin.error(new PluginResult(
											Status.JSON_EXCEPTION), callBackId);
								}
								datePickerPlugin.success(new PluginResult(
										PluginResult.Status.OK, userChoice),
										callBackId);

							}
						}, 1, 1, true);

				tpd.show();
			}
		};
		ctx.runOnUiThread(runnable);

	}

	public synchronized void showDatePicker(final String callBackId) {

		final DatePickerPlugin datePickerPlugin = this;
		final Context currentCtx = cordova.getActivity();
		final Calendar c = Calendar.getInstance();
		final int mYear = c.get(Calendar.YEAR);
		final int mMonth = c.get(Calendar.MONTH);
		final int mDay = c.get(Calendar.DAY_OF_MONTH);

		final Runnable runnable = new Runnable() {

			public void run() {
				final DatePickerDialog dpd = new DatePickerDialog(currentCtx,
						new OnDateSetListener() {

							public void onDateSet(final DatePicker view,
									final int year, final int monthOfYear,
									final int dayOfMonth) {

								final JSONObject userChoice = new JSONObject();

								try {
									userChoice.put("year", year);
									userChoice.put("month", monthOfYear);
									userChoice.put("day", dayOfMonth);
								} catch (final JSONException jsonEx) {
									Log.e("showDatePicker",
											"Got JSON Exception "
													+ jsonEx.getMessage());
									datePickerPlugin.error(new PluginResult(
											Status.JSON_EXCEPTION), callBackId);
								}

								datePickerPlugin.success(new PluginResult(
										PluginResult.Status.OK, userChoice),
										callBackId);

							}
						}, mYear, mMonth, mDay);

				dpd.show();
			}
		};
		ctx.runOnUiThread(runnable);
	}

}


Add in config.xml:

<plugins>
        <plugin name="DatePickerPlugin" value="org.apache.cordova.DatePickerPlugin"></plugin>
    </plugins>

phonegap-datePicker.js:

/**
 * 日期插件
 * 
 * @author cjianquan
 * @since 2014-07-16
 * 
 */
var DatePicker = function() {
};
DatePicker.prototype.showDateOrTime = function(action, successCallback,
		failureCallback) {
	return PhoneGap.exec(successCallback, // Success callback from the plugin
	failureCallback, // Error callback from the plugin
	'DatePickerPlugin', // Tell PhoneGap to run "DatePickerPlugin" Plugin
	action, // Tell plugin, which action we want to perform
	[]); // Passing list of args to the plugin
};

/**
 * Enregistre une nouvelle bibliothèque de fonctions auprès de PhoneGap
 */

PhoneGap.addConstructor(function() {
	// 如果不支持window.plugins,则创建并设置
	if (!window.plugins) {
		window.plugins = {};
	}
	window.plugins.datePickerPlugin = new DatePicker();
	// 向phonegap中注入插件相关的js
	// Register the javascript plugin with PhoneGap
	PhoneGap.addPlugin('datePickerPlugin', new DatePicker());
	// phonegap中注入后台插件相关的java类
	// Register the native class of plugin with PhoneGap
	PluginManager.addService("DatePickerPlugin",
			"org.apache.cordova.DatePickerPlugin");
});

In html page:

<script type="text/javascript" src="WellApp/lib/phoneGap/phonegap-datePicker.js"></script>
<script type="text/javascript">

	$("#dob").click(function(){  
	              window.plugins.datePickerPlugin.showDateOrTime(  
	                    'date',  
	                    function(r){  
	                    	$("#dob").val(r.year+"-"+(r.month+1) +"-"+r.day);
	                    },  
	                    function(e){console.log(e);}  
	                );  
	        });  

</script>



Reproduced in: https: //my.oschina.net/u/2552902/blog/543902

Guess you like

Origin blog.csdn.net/weixin_33779515/article/details/92326943