android how to show PopupMenu in webview like GMail - javascript

I want to show PopupMenu in webview on my app like GMail.
Here is my code:
webView.addJavascriptInterface(new WebAppInterface(getActivity()), "ScriptToAndroid");
<div class="moreover_icon" onclick="showPopup('file_attach_path', event)">
<img class="overflow_icon" src="android_moreover_icon"/>
</div>
<script type="text/javascript">
function showPopup(file_path, event) {
ScriptToAndroid.showPopupDialog(file_path, pos_x, pos_y);
}
</script>
#JavascriptInterface
public void showPopupDialog(String filePath, int x, int y) {
//show PopupMenu
}

Use a WebViewClient
mWebView = (WebView) findViewById(R.id.webView);
mWebView.setWebViewClient(new WebClient(this));
intercept shouldOverrideUrlLoading()
public class WebClient extends WebViewClient {
MainActivity mainActivity;
public WebClient(MainActivity activity) {
mainActivity = activity;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("xxx")) {
Log.i("show pop", "xx");
}
return false;
}
#Override
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return super.shouldOverrideKeyEvent(view, event);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
}
}

Related

Chrome Custom Tab get content and page event listener

I'm developing an Android app. In past projects, I used to use WebView to show web content. This gave me the capability to intercept events like page loaded and so on. The important thing that I was able to do was to get page content and use it in the Java code. To be honest, I use a trick, but it works. I put the essential code of my fragment to use a WebView to open an URL, do something and when the user arrives in a specific page and get the page content (with MyJavaScriptInterface):
public class LoginFragment extends MyAppFragment {
#BindView(R.id.webView)
public WebView webView;
public LoginFragment() {
}
#Override
public void onResume() {
super.onResume();
webView.setVisibility(View.VISIBLE);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
initBinder(rootView);
...
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.setWebViewClient(mWebViewClient);
/* Register a new JavaScript interface called HTMLOUT */
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.loadUrl(getResources().getString(R.string.url_login).trim());
return rootView;
}
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String token) {
if (token.contains(URL_LANDING)) {
...
}
}
}
private WebViewClient mWebViewClient = new WebViewClient() {
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Logger.info("shouldInterceptRequest " + request.getUrl().toString());
if (URL_LANDING_SESAPP.equals(request.getUrl().toString())) {
...
}
return super.shouldInterceptRequest(view, request);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
...
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onLoadResource(WebView view, String url) {
...
super.onLoadResource(view, url);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
...
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
...
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pageLoading = false;
if (loginDone) {
view.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('body')[0].innerHTML);")
}
}
};
}
Is there an equivalent way to do this with Chrome Custom Tags? Thank you in advance.

How to replace a body in html file

I'm using android studio
I need to replace the body of an html document with other codes, this is an example that I tried to follow
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grafico);
wv = (WebView) findViewById(R.id.prova);
wv.setWebViewClient(new MyWebViewClient());
new BackgroundWorker().execute();
}
// load links in WebView instead of default browser
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#RequiresApi(21)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
}
private class BackgroundWorker extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
getDarewod();
return null;
}
public void getDarewod() {
try {
Document htmlDocument = Jsoup.connect(url).get();
Element element = htmlDocument.select("#gkHeaderMod > div.grafico-quotazione").first();
// replace body with selected element
htmlDocument.body().empty().append(element.toString());
final String html = htmlDocument.toString();
uiHandler.post(new Runnable() {
#Override
public void run() {
wv.loadData(html, "text/html", "UTF-8");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
I want to replace the all body with the code in my element variable. However this line doesn't works. How can I do?
htmlDocument.body().empty().append(element.toString());

How to call admob Interstitial ad from android webview JavascriptInterface

I was facing problem for calling android Admob interstitial from webview. I could not get any proper solution. Finally I figured out the solution to call the interstitial for javascript. Look into the below answer.
Solution for the above problem
Import all the required packages.
public class MainActivity extends AppCompatActivity {
WebView myWevView;
public InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
myWevView =(WebView)findViewById(R.id.myWevView);
WebSettings ws= myWevView.getSettings();
ws.setJavaScriptEnabled(true);
ws.setDomStorageEnabled(true);
myWevView.getSettings().setUseWideViewPort(true);
myWevView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWevView.setWebViewClient(new WebViewClient());
myWevView.setWebChromeClient(new WebChromeClient());
myWevView.getSettings().setBuiltInZoomControls(true);
myWevView.loadUrl("file:///android_asset/index.html");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
}
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
public void displayLoadedAd(){
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
else
Toast.makeText(getApplicationContext(), "Ad not loded", Toast.LENGTH_SHORT).show();
}
});
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showAdFromJs(){
Toast.makeText(mContext, "Loading Ad", Toast.LENGTH_SHORT).show();
displayLoadedAd();
}
}
//Controlling navigation
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (myWevView.canGoBack()) {
myWevView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
calling from javascript
$("#btn1").click(function(){
Android.showAdFromJs();
});
I used this without the javascript call like this:
#Override
public void onAdLoaded(){
displayLoadedAd();
}
You would need to lower the number of interstitial ads to your pref. in your admob console.

Jquery and CSS animation not working in ANDROID Webview application

I am trying to make a Webview for my website. But i have one problem with jquery code.
This is my DEMO site. In this demo site you can see when you click the image then detail div will open with animation.
But that detail is not open when i click the image.
Note: I am a new in Android
Here is my application code for Webview:
package ecowebtr.ecowebtr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webView;
private CustomWebViewClient webViewClient;
private String Url = "http://www.ecowebtr.com/";
ProgressDialog mProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading...");
webViewClient = new CustomWebViewClient();
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(webViewClient);
webView.loadUrl(Url);
}
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(!mProgressDialog.isShowing())
{
mProgressDialog.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
}
}
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
Try this code to solve:
webView = (WebView) findViewById(R.id.web);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
settings.setDatabasePath("/data/data/" + this.getPackageName() + "/databases/");
}

Webview Fragment : Back button and Download Listener?

I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}

Categories