How do I add a confirm AlertDialog in a Rubymotion webview?

28 Views Asked by At

Using the android webview template there is an example for handling js alerts.

class MyWebChromeClient < Android::Webkit::WebChromeClient
  def onJsAlert(view, url, message, result)
    puts message
    result.confirm
    true
  end
end

How would I implement this for confirm with the builtin Dialog.Builder?

1

There are 1 best solutions below

0
user11013897 On

The trick was to pass the view.context to the Builder and add listeners that handle the onClick:

class MyWebChromeClient < Android::Webkit::WebChromeClient
  def onJsConfirm(view, url, message, result)
    builder = Android::App::AlertDialog::Builder.new(view.context)
    builder.message = message
    builder.setPositiveButton(Android::R::String::Ok, ConfirmListener.new(result))
    builder.setNegativeButton(Android::R::String::Cancel, CancelListener.new(result))
    builder.show
    true
  end
end

class ConfirmListener
  attr_reader :result
  def initialize(result)
    @result = result
  end

  def onClick(dialog, id)
    result.confirm
  end
end

class CancelListener
  attr_reader :result
  def initialize(result)
    @result = result
  end

  def onClick(dialog, id)
    result.cancel
  end
end