按下Android后退按钮时如何显示确认提示?

时间:2015-04-13 18:41:44

标签: android titanium titanium-mobile titanium-alloy

我想在Android上按下后退按钮时在Webview页面上实现警报。我应该使用什么代码?

我在view1.js中写了下面的代码,但是在Android警报上按下后退按钮没有显示,它只是进入主屏幕:

$.webview1.url=Alloy.Globals.baseurl;
if(Ti.Platform.osname=='android'){
    $.webview1.enableZoomControls=false;
}

$.webview1.addEventListener('androidback',function(e){
    // show alert
    alert("Do you want to exit?");
    dialog.show();
});

但它不起作用。任何解决方案?

3 个答案:

答案 0 :(得分:1)

检查出来:

$.index.addEventListener('androidback', function(e) {
       if ($.webview1.canGoBack())
           $.webview1.goBack();
       else
           alert('open alert');
});

答案 1 :(得分:0)

试试这个:

//create window
var window = Titanium.UI.createWindow();

//create webview
var webview = Titanium.UI.createWebView({
    height : Ti.UI.FILL,
    width : Ti.UI.FILL,
    url : 'http://stackoverflow.com/'
});

//add webview
window.add(webview);

//add event listener
window.addEventListener('androidback', function(e) {
    alert('open alert');
});

window.open();

文档: http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.UI.Window-event-androidback

答案 2 :(得分:0)

WebView没有点击Android后退按钮的事件,但是Window没有,这就是它没有显示警告对话框的原因。

dialog.show();中还有另一个错误,我没有看到您对该对话框进行初始化,而且您之前也正在调用警报。 alert不需要调用任何要显示的内容,但AlertDialog会显示,并且用户最好看到标题而不是单词alert,所以如果它会一直使用AlertDialog处理用户。

请尝试以下代码:

index.xml文件:

<Alloy>
    <Window id="win" onAndroidback="showExitDialog">
        <WebView id="webView" url="http://www.google.com" />
    </Window>
    <AlertDialog id="dialog" onClick="dialogClicked" title="Exit"
        message="Sure to exit?" cancel="1">
        <ButtonNames>
            <ButtonName>Confirm</ButtonName>
            <ButtonName>Cancel</ButtonName>
        </ButtonNames>
    </AlertDialog>
</Alloy>

index.js文件应如下所示:

$.win.open();
function showExitDialog() {
    $.dialog.show();
}

function dialogClicked(e) {
    if(e.index == 0) { // If the user clicked confirm
        $.win.close(); // Close the window or do whatever you want here
    }
}

我建议阅读文档,一切都在那里,检查WebViewWindowAlertDialog文档。