使用javascript从片段内的webview调用日历

时间:2015-07-03 06:41:14

标签: android webview android-calendar

我按照How To Make Material Design Sliding Tabs中描述的方法创建了滑动标签,这非常有效。根据我的要求,我已更新其中一个选项卡类以包含WebView。此webview显示一个html页面。当我点击html页面上的按钮时,我需要调用日历活动。我创建了以下类来实现这一目标。

我的Tab2类

public class Tab2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tab_2,container,false);

    MyWebView browser= (MyWebView) v.findViewById(R.id.my_browser);

    WebSettings webSettings = browser.getSettings();
    webSettings.setJavaScriptEnabled(true);

    browser.addJavascriptInterface(new AddtoCalendarInterface(getActivity().getBaseContext()), "Android");



//I plan to replace the local html file with a real webpage 
    browser.loadUrl("file:///android_asset/events.html");

    return v;

  }

}

我的MyWebView类

public class MyWebView extends WebView {
  public MyWebView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
  }

public MyWebView(Context context, AttributeSet attrs)
{
 super(context, attrs);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
   onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
  return super.onTouchEvent(event);
}

public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
}
}

我的AddtoCalendar接口类

public class AddtoCalendarInterface extends Activity {

Context m_context;

AddtoCalendarInterface(Context _mContext)
{
    m_context = _mContext;
}


   /** Instantiate the interface and set the context */
    AddtoCalendarInterface () {

    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Calendar beginTime = Calendar.getInstance();
        beginTime.set(2012, 0, 19, 7, 30);
        Calendar endTime = Calendar.getInstance();
        endTime.set(2012, 0, 19, 8, 30);
        Intent intent = new Intent(Intent.ACTION_INSERT)
                .setData(Events.CONTENT_URI)
                .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
                .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
                .putExtra(Events.TITLE, "Title")
                .putExtra(Events.DESCRIPTION, "Description")
                .putExtra(Events.EVENT_LOCATION, "Location")
                .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
                .putExtra(Intent.EXTRA_EMAIL, "example@example.com");

        Toast.makeText(m_context, "AddTocalendar", Toast.LENGTH_LONG).show();
         m_context.startActivity(intent);

    }
}

HTML文件中的代码

input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
    Android.showToast(toast);
}
</script>

Toast会显示但不会显示日历意图。

感谢您解决此问题的任何帮助。

由于

0 个答案:

没有答案