Popup above action bar - java

I'm trying to align the popup to under the action bar and I don't find any solution, I already seen some videos and nothing, please help me, I'm starting to program and I'm really noob at this, here is my print screen of the problem:
https://i.stack.imgur.com/mdHDx.png
Here is my code:
public class MainActivity extends AppCompatActivity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(this), "android");
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(MainActivity.this, "Gear Track", "Loading...");
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url){
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url){
Log.i(TAG, "Finished loading url: " +url);
if (progressBar.isShowing()){
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Log.e(TAG, "Error: " + description);
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.show();
}
});
webview.loadUrl("https://geartrack.hdn.pt");
}
public class WebAppInterface{
Context mContext;
WebAppInterface(Context c){
mContext = c;
}
#JavascriptInterface
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.action_refresh:
webview.loadUrl("https://geartrack.hdn.pt");
return true;
case R.id.action_about:
startActivity(new Intent(this, About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<item
android:id="#+id/action_refresh"
android:checkable="true"
android:enabled="true"
android:icon="#drawable/ic_action_name"
android:title="Refresh"
android:visible="true"
app:showAsAction="always" />
<item
android:id="#+id/action_about"
android:title="About"
app:showAsAction="never"/>
</menu>

Related

Webview Bookmark

I am trying to add bookmark in my web browser and have added it but , it is only saving 1 link . for example if I am at https://www.wikipedia.org/ and save this bookmark
and i browse wikipedia more and landed on this link https://en.wikipedia.org/wiki/Portal:Featured_content
the bookmark will show remove in snack bar and is just saving 1 link and removing 1 link
I want to save both links.
public static final String PREFERENCES = "PREFERENCES_NAME";
public static final String WEB_LINKS = "links";
public static final String WEB_TITLE = "title";
String murl;
//
CoordinatorLayout coordinatorLayout;
private ProgressBar progressBar;
//
android.webkit.WebView webView;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (android.webkit.WebView) findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
initWebview();
WebSettings settings = webView.getSettings();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
murl = getIntent().getExtras().getString("url");
coordinatorLayout = findViewById(R.id.main_content);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// zoom
settings.setBuiltInZoomControls(true);
// zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDomStorageEnabled(true);
webView.setScrollBarStyle(webView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(murl);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
// webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.saved, menu);
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String links = sharedPreferences.getString(WEB_LINKS, null);
if (links != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
menu.getItem(0).setIcon(R.drawable.bookmark);
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_bookmark) {
String message;
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
linkList.remove(murl);
titleList.remove(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "removed";
} else {
linkList.add(murl);
titleList.add(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(murl);
titleList.add(webView.getTitle());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void initWebview() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
murl = url;
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
}
xml file :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Link inside webpage always return "404 not found" error if opened from webview ~Android ~Java

I have a webview that opens up a webpage that contains a some links. However, if I click on each link, it will show "404 Not Found" error. I have done the shouldOverrideUrlLoading inside WebViewClient, but it results the same.
Please help. Thanks in advance.
this is how I set my webview:
WebView web_view = (WebView)view.findViewById(R.id.web_view);
WebSettings webSettings = web_view.getSettings();
web_view.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
});
web_view.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void shouldOverrideUrlLoading(Webview view, String url){
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
return super.shouldOverrideUrlLoading(view,url);
}
})
webSettings.setJavaScriptEnabled(true);
web_view.loadUrl("http://someurl.com");
I have also done this:
#Override
public void shouldOverrideUrlLoading(Webview view, String url){
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
but both of them result in '404 not found'.
Any help please..
Prepare the layout to show when an error occurred instead of Web Page (a dirty 'page not found message') The layout has one button, "RELOAD" with some guide messages.
If an error occurred, Remember using boolean and show the layout we prepare.
If user click "RELOAD" button, set mbErrorOccured to false. And Set mbReloadPressed to true.
if mbErrorOccured is false and mbReloadPressed is true, it means webview loaded page successfully. 'Cause if error occurred again, mbErrorOccured will be set true on onReceivedError(...)
Here is my full source. Check this out.
public class MyWebViewActivity extends ActionBarActivity implements OnClickListener {
private final String TAG = MyWebViewActivity.class.getSimpleName();
private WebView mWebView = null;
private final String URL = "http://www.google.com";
private LinearLayout mlLayoutRequestError = null;
private Handler mhErrorLayoutHide = null;
private boolean mbErrorOccured = false;
private boolean mbReloadPressed = false;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
((Button) findViewById(R.id.btnRetry)).setOnClickListener(this);
mlLayoutRequestError = (LinearLayout) findViewById(R.id.lLayoutRequestError);
mhErrorLayoutHide = getErrorLayoutHideHandler();
mWebView = (WebView) findViewById(R.id.webviewMain);
mWebView.setWebViewClient(new MyWebViewClient());
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(getChromeClient());
mWebView.loadUrl(URL);
}
#Override
public boolean onSupportNavigateUp() {
return super.onSupportNavigateUp();
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btnRetry) {
if (!mbErrorOccured) {
return;
}
mbReloadPressed = true;
mWebView.reload();
mbErrorOccured = false;
}
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
else {
finish();
}
super.onBackPressed();
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (mbErrorOccured == false && mbReloadPressed) {
hideErrorLayout();
mbReloadPressed = false;
}
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mbErrorOccured = true;
showErrorLayout();
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
private WebChromeClient getChromeClient() {
final ProgressDialog progressDialog = new ProgressDialog(MyWebViewActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
return new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
};
}
private void showErrorLayout() {
mlLayoutRequestError.setVisibility(View.VISIBLE);
}
private void hideErrorLayout() {
mhErrorLayoutHide.sendEmptyMessageDelayed(10000, 200);
}
private Handler getErrorLayoutHideHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
mlLayoutRequestError.setVisibility(View.GONE);
super.handleMessage(msg);
}
};
}
}
try this... this is the code from AS default webview activity, generated by AS.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.google);
initInstances();
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
}
sidenote :-->> iinitInstances() is referring to nagivation drawer on the left, could be ignored.

How to add progress bar line in webview

I am trying to add a progress bar or loading bar to my application which uses webview. I have to application set up to run all the links within the app but i am confused on how to implement a progress bar for whenever a link is clicked on
this is my code
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://caknowledge.in");
mWebView.setWebViewClient(new MyAppWebViewClient());
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyAppWebViewClient extends WebViewClient {
}
And XML.JAVA Code is as below
<WebView android:id="#+id/activity_main_webview" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
just use progressBar above your webview and when your web view start loading page make it visiible and when your webview page loaded hide the progressbar
you can add below code on your webviewclient to show progress dialog
private class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView p_view, String p_url, Bitmap p_favIcon)
{
try {
if (progressDialog != null && !isFinishing())
progressDialog.show();
} catch (Throwable ex) {
//ignore
}
super.onPageStarted(p_view, p_url, p_favIcon);
}
#Override
public void onPageFinished(WebView p_view, String p_url)
{
try {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Throwable ex) {
//ignore
}
super.onPageFinished(p_view, p_url);
}
}
Progress bar declaration in activity
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
Hope it works for you !!
layout code
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"/>
<WebView
android:layout_below="#id/progress_bar"
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
java code
webView.setWebViewClient(new HelloWebViewClient());
progressBar.setVisibility(View.INVISIBLE);
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
// TODO show you progress image
progressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{ progressBar.setVisibility(View.INVISIBLE);
// TODO hide your progress image
super.onPageFinished(view, url);
}
}

Android, WebView not playing YouTube videos [duplicate]

YouTube Video not playing in WebView.
It my first app ,I Want to do a webview.
When I open YouTube the video not playing, is loading but not playing.
Is loading all the time.
Thank you so much for helping.
Java:
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
} }
Xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Seems like duplicate of play youtube video in WebView and YouTube Video not playing in WebView - Android
To make it work via WebView, I used the following two steps (version 4.2.2/Nexus 4):
On shouldOverrideUrlLoading I added webview.setWebChromeClient(new WebChromeClient());
In AndroidManifest.xml for activity tag I added android:hardwareAccelerated="true"
AndroidManifest.xml should also contain Internet permission.
While exact steps with playing video via WebView can be specific to device and Android version, there are also other alternatives to WebView, like VideoView or using Youtube Android Player API.
EDIT1
As for pause and full screen, this is actually a second link I mentioned in the beginning. To make it easier, I am posting code that worked on my Nexus.
In activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fullscreen_custom_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"/>
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
In MainActivity class:
public class MainActivity extends Activity {
private WebView mWebView;
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.setWebChromeClient(new WebChromeClient() {
private View mCustomView;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
// if a view already exists then immediately terminate the new one
if (mCustomView != null)
{
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
});
webview.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
EDIT2 - adding back button support
public class MainActivity extends Activity {
private WebView mWebView;
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
// if a view already exists then immediately terminate the new one
if (mCustomView != null)
{
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView()
{
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
#Override
protected void onStop() {
super.onStop();
if (mCustomView != null)
{
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (mCustomView != null)
{
mWebChromeClient.onHideCustomView();
} else
{
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Adding webchrome client solves the issue,
web = (WebView) vi.findViewById(R.id.offer_webView1);
web.loadUrl(getResources().getString(R.string.videolink));
web.getSettings().setJavaScriptEnabled(true);
// web.getSettings().setDomStorageEnabled(true);
web.getSettings().setAllowContentAccess(true);
WebSettings webSettings = web.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
web.canGoBack();
web.setWebChromeClient(new WebChromeClient() {});

How don't kill process after onStop?

Simple code:
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private int a;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
final WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
webviewtwoSettings.setTextSize(TextSize.NORMAL);
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Now My problem. After i press back button onStop() code is executed and onDestroy. How i can don't kill app ? I wanna this app in background. Now when i press back button and open app, all data is again downloaded and loaded to webview. Soo how make this process work in background ?
Sorry for my haotic english :)
Sierran
Use Android service for doing something in Background rather then Activity.
And use Broadcast receiver to invoke your Activity from service. When something your background work finished.
Android - Service
And if you want to do some little then just override onKeyDown()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
return true;
}
return super.onKeyDown(keyCode, event);
}
I would recommend using a Service if you want to do something in the background and need it to be running more or less all the time. Check out the Service documentation here:
http://developer.android.com/reference/android/app/Service.html
An alternative in your case would be to create local caches of the websites.

Categories