2. 攔截點擊"返回鍵"事件,給予相對的反應。
3. 離開程式時,詢問是否離開。
-------------------------------------------
接下來第三部份,當使用者離開程式時,詢問是否離開。
也就是在需要離開程式時,跳出附有Button的AlertDialog,讓使用者選擇是否離開。
上圖的case1就是跳出的確認視窗,當使用者確定要離開時,則執行OlaTeach_WebView.this.finish()來離開Activity。case2就是該篇所顯示的ProgressDialog。
執行結果:
最後貼上三篇所有程式碼:
package ola.OlaTeach_WebView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class OlaTeach_WebView extends Activity {
/** Called when the activity is first created. */
private WebView OlaWebView;
private TextView lab1;
private ProgressDialog Pd;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
boolean CloseYN;
if (OlaWebView.canGoBack())
{
CloseYN = false;
OlaWebView.goBack();
}
else
{
show(1);
CloseYN = true;
}
event.startTracking();
return CloseYN;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strURI = "http://10.172.50.2/SSCenter_Web_C/SSCenterMain.aspx";
//String strURI = "http://tinyurl.com/yz3j7sc";
OlaWebView = (WebView) findViewById(R.id.myWebView1);
lab1 =(TextView) findViewById(R.id.TextView01);
OlaWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
lab1.setText("努力中");
show(2);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
lab1.setText("呼~~~完成");
Pd.hide();
super.onPageFinished(view, url);
}
});
OlaWebView.loadUrl(strURI);
}
public void show(int id) {
switch(id){
case 1:
new AlertDialog.Builder(OlaTeach_WebView.this)
.setTitle("你確定?")
.setMessage("要離開我了? T.T")
.setPositiveButton("沒錯",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
OlaTeach_WebView.this.finish();
}
})
.setNegativeButton("再留一下",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
break;
case 2:
Pd=new ProgressDialog(OlaTeach_WebView.this);
Pd.setTitle("我在讀取、別催我");
Pd.setMessage("努力中....");
Pd.show();
break;
default:
break;
}
}
}