ad728

Sunday, September 4, 2016

AIDE Tutorial - 20.3 WebView with exit Alert Dailog

Java



package com.kc.webview3;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.webkit.*;

public class MainActivity extends Activity
{
private FrameLayout fl;
private ProgressBar pb;
private WebView web;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
web=(WebView) findViewById(R.id.web);
pb=(ProgressBar)findViewById(R.id.pb);
fl=(FrameLayout)findViewById(R.id.fl);

WebSettings WebSettings=web.getSettings();
WebSettings.setJavaScriptEnabled(true);
web.loadUrl("http://shyamkumarkc.blogspot.com");
web.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView View, String url){
fl.removeView(pb);
}
});
}
@Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if(web.canGoBack()) {
            web.goBack();
        } else {
         

AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you want to exit?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{
MainActivity.this.finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert =builder.create();
alert.show();
}
}
}

Manifest
<uses-permission android:name="android.permission.INTERNET"/>

Main xml





<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
android:id="@+id/fl">


    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/pb"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>




Share:

0 comments:

Post a Comment

Total Pageviews

Sponsor

Sponsor

ad300