2 cheli 71 cheli_71 于 2013.08.26 11:55 提问

点击 Javascript 中的按钮显示 DatePicker

我想加载一个 html 文件到 WebView,在 html文件上有一个按钮来选择日期。当我点击按钮时,我想打开日期选择器对话框。再选择日期后,我想在html文件中显示选择的日期。如何实现?
HTML :

<input type="button" value="Select Date" onClick="openDatePickerDialog()" />
 <p id = "date">--</p>

Javascript :

function openDatePickerDialog() {
   AndroidFunction.openDatePickerDialog();
 }

function callFromActivity(date) {
document.getElementById('date').innerHTML = date;
 }

My Activity :

 public class MainActivity extends Activity {
WebView myBrowser;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myBrowser = (WebView)findViewById(R.id.mybrowser);

    final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
    myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

    myBrowser.getSettings().setJavaScriptEnabled(true); 

    myBrowser.loadUrl("file:///android_asset/test.html");      



}

public class MyJavaScriptInterface 
{
    private int mYear;
    private int mMonth;
    private int mDay;
    static final int DATE_DIALOG_ID = 0;

    Context mContext;

    MyJavaScriptInterface(Context c)
    {
        mContext = c;
    }


    public void openDatePickerDialog()
    { 
        Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        //updateDisplay();

        showDialog(DATE_DIALOG_ID);
    }
    private void updateDisplay() {

        String date = new StringBuilder().append(mMonth + 1).append("-")
        .append(mDay).append("-")
        .append(mYear).append(" ").toString();

        Toast.makeText(getApplicationContext(), date, Toast.LENGTH_LONG).show();

        myBrowser.loadUrl("javascript:callFromActivity(\""+date+"\")");
    }


    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, 
                int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
    };


    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(MainActivity.this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
        }
        return null;
    }

}
 }
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!