Webview load data before onClick - android

my project working like
Showing activity main and im older than 13 years ago button. If u click button opening website some horror films.
Opening webview and loading website.
now my fail here.the user clicked button and waiting 5-6 second ? i want to make this like
Showing activity_main and click button (and loading website background)
Showing webview not waiting page was loaded !
Activity_main (first)
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent it=new Intent(new Intent(MainActivity.this, web.class)) ;
startActivity(it);
}
});
}
web.class
public class web extends Activity {
private WebView webView;
private View mCustomView ;
private myWebViewClient mWebViewClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http:/zzzzzz..x.x.x.x..x.x");
final ConnectivityManager connMgr = (ConnectivityManager) web.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected() || mobile.isConnected()) {
return;
}else{
setContentView(R.layout.main);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
}
}
activity main (manitibo)
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Onaylıyorum" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_centerHorizontal="true"
android:text="Uyarı !"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignLeft="#+id/button1"
android:text="Onaylıyorum butonuna bastığınızda 18 yaş ve üzeri olduğunuzu kabul etmiş sayılırsınız !"
android:textAppearance="?android:attr/textAppearanceMedium" />
<WebView
android:id="#+id/webView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:visibility="gone" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="Destek: xxxxxxxxxxx"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2"
android:layout_marginTop="18dp"
android:src="#drawable/asdaa" />
</RelativeLayout>

I would have done something like that:
public class MainActivity extends Activity
{
// Layout elements
private Button btn_aboveage = null;
private WebView webView = null;
private myWebViewClient mWebViewClient = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Attach layout
setContentView(R.layout.activity_main);
// Retrieve layout elements
btn_aboveage = (Button) findViewById(R.id.btn_aboveage);
webView = (WebView) findViewById(R.id.webView);
// Load page
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http:/zzzzzz..x.x.x.x..x.x");
// Check Internet connectivity
if (!hasInternet())
{
// TODO : Display alert dialog !
}
// Attach listener
btn_aboveage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
webView.setVisibility(View.VISIBLE);
btn_aboveage.setVisibility(View.VISIBLE);
// TODO : Hide layout elements you don't want to be displayed while in webview mode.
}
});
}
private boolean hasInternet()
{
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return (wifi.isConnected() || mobile.isConnected());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if (webView != null && webView.getVisibility() == View.VISIBLE && webView.canGoBack())
{
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private static class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return super.shouldOverrideUrlLoading(view, url);
}
}
}
And finally the layout I use.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<WebView
android:id="#+id/webView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:visibility="gone" />
<Button
android:id="#+id/btn_aboveage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignVertical="true"
android:text="I'm above 13" />
</RelativeLayout>

Related

Add forward and back button on a custom toolbar

I am trying to add forward and back button on custom toolbar in android studio I have tried adding it as a menu as well as separate buttons but every time when I run the app the buttons are not appearing. Code is working fine I am not able to detect what am i missing here. Here is the code :
XML
<LinearLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/toolbar01"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="0.4"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:src="#drawable/menu"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3">
<Button
android:id="#+id/back"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_back_ios_24">
</Button>
<Button
android:id="#+id/forward"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_forward_ios_24">
</Button>
<Button
android:layout_marginLeft="50dp"
android:id="#+id/refresh"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_refresh_24"
android:layout_marginStart="40dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:progress="50"
android:progressTint="#color/colorPrimary"
android:indeterminate="true"
android:indeterminateDuration="2000"
android:maxHeight="3dp"
android:minHeight="3dp"
tools:targetApi="lollipop" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
>
<WebView
android:id="#+id/webView"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
JAVA:
public class Webview extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private WebView webview;
NavigationView navigationView;
DrawerLayout drawer;
ImageView menuicon, forward, back, refresh;
static final float END_SCALE = 0.7f;
LinearLayout contentView;
ProgressBar progressBar;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
navigationDrawer();
Loadweb();
}
private void toolbuttons() {
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onForwardPressed();
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webview.reload();
}
});
}
private void Loadweb() {
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
}
});
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
progressBar.setMax(100);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
webview.reload();
}
}, 3000);
}
});
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private void navigationDrawer() {
//navigation view
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
menuicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerVisible(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else drawer.openDrawer(GravityCompat.START);
}
});
animateNavigationDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
webview.reload();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerVisible(GravityCompat.START) || webview.canGoBack()) {
drawer.closeDrawer(GravityCompat.START);
webview.goBack();
} else {
super.onBackPressed();
}
}
public void onForwardPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
Toast.makeText(this, "Can't go back", Toast.LENGTH_SHORT).show();
}
}
private void animateNavigationDrawer() {
drawer.setScrimColor(getResources().getColor(R.color.colorPrimary));
//Add any color or remove it to use the default one!
//To make it transparent use Color.Transparent in side setScrimColor();
//drawerLayout.setScrimColor(Color.TRANSPARENT);
drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Scale the View based on current slide offset
final float diffScaledOffset = slideOffset * (1 - END_SCALE);
final float offsetScale = 1 - diffScaledOffset;
contentView.setScaleX(offsetScale);
contentView.setScaleY(offsetScale);
// Translate the View, accounting for the scaled width
final float xOffset = drawerView.getWidth() * slideOffset;
final float xOffsetDiff = contentView.getWidth() * diffScaledOffset / 2;
final float xTranslation = xOffset - xOffsetDiff;
contentView.setTranslationX(xTranslation);
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
} else if (id == R.id.nav_privacy_policy) {
webview.loadUrl("https://www.nationalsavings.com.pk/privacy-policy.php");
} else if (id == R.id.nav_share) {
Intent shareintent = new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT, "https://www.nationalsavings.com.pk/index.php");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent, "Share via"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Progress bar and No internet connection in webview Fragment

I am trying to get a progress bar which shows until the web page is loaded. and if user has no internet connection than a text or toast is showed... but i am unable to get it worked.. searched the whole website. i think its easy to add progress bar to class that expends Activity...
here is my class and layout
package com.nirav.rpta.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.nirav.rpta.R;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
WebSettings webSettings = heroespage.getSettings();
webSettings.setJavaScriptEnabled(true);
heroespage.loadUrl("http://google.co.in/");
return rootView;
}}
and my layout
<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"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/></RelativeLayout>
Add a ProgressBar to your layout file:
<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"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminate="true"/>
</RelativeLayout>
Now in the code:
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
ProgressBar loading = (ProgressBar) rootView.findViewById(R.id.progress);
heroespage.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
loading.setVisibility(View.GONE);
heroespage.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Show error toast
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// Show error toast
}
});
heroespage.loadUrl("http://google.co.in/");
Please check below code for the thing you want.
Your layout
<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"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<ProgressBar
android:id="#+id/progressBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Your Java file should be like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
// Resources
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar2);
WebSettings settings = heroespage.getSettings();
settings.setJavaScriptEnabled(true);
heroespage.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.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Log.e(TAG, "Error: " + description);
Toast.makeText(WebViewScreen.this, "You are offline.",
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
}
});
heroespage.loadUrl(URL);
return rootView;
}}
You must update your layout
<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"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/progbar"/>
</RelativeLayout>
And then find id of progressbar ProgressBar prog = view.findViewById(R.id.progbar);
to check internet connection use this method
public boolean isConnectingToInternet( Context _context){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
add this code in your oncreateview
heroespage.setWebViewClient(new WebViewCLient(){
public void onPageLoadFinished(){
progbar.setvisibility(View.Gone);
});
if(isconnectingInternet(getActivity()){
heroespage.loadUrl("http://google.co.in/");
}else{
// show your toast here
}
to hide / show progress bar you can use setWebViewClient which provide onPage strated and onPageFinished method
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Show Progress bar
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// hide Progress bar
}
});
To check no internet connection , you can use below code
public static boolean isNetConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
}
return false;
}
Use above method before loading url
if(isNetConnected()) {
heroespage.loadUrl("http://google.co.in/");
} else {
Toast.makeText(getActivity() ,"No internet connection",Toast.LENGTH_SHORT).show();
}

On Item Click opens RSS links in webview

In an RSS fragment I have, the following code that I believe dictates what happens when an item in the RSS list view is created. When an item is clicked it is opened in chrome.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
I would like the link to be opened in a webview activity that I have already created, which currently only loads one webpage, google. This is the webview activity code:
public class WebViewActivity extends ActionBarActivity {
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
web = (WebView) findViewById(R.id.webview);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("https://www.google.com");
web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
web.getSettings().setLoadWithOverviewMode(true);
web.getSettings().setUseWideViewPort(true);
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, MainActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}
#Override
public void onBackPressed() {
startActivity(new Intent().setClass(WebViewActivity.this, MainActivity.class).setData(getIntent().getData()));
return;
}
}
The XML layout for:
Rss Fragment
<FrameLayout 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" tools:context="yanay.end.TwitterFragment"
android:background="#color/white"
android:paddingLeft="3dp"
android:paddingRight="3dp">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:paddingRight="0dp"
android:paddingLeft="0dp"
android:paddingTop="0dp"
android:paddingBottom="1dp"
android:layout_height="fill_parent"
android:divider="#color/blue1"
android:dividerHeight="3dp"
>
</ListView>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
</FrameLayout>
And the Web view layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
/>
</RelativeLayout>
EDIT: Now clicking the link opens the web activity, but I still cannot figure out how to set the url to the clicked items url.
place the below code in the onItemClick of RSSFragment
String urlval = uri + "";
Intent mIntent = new Intent(getActivity(), WebViewActivity.class);
mIntent.putExtra(WebViewActivity.URL_KEY, urlval);
startActivity(mIntent);
below code in the WebViewAcitivity
Bundle extras = getIntent().getExtras();
String url = extras.getString(URL_KEY);
web.loadUrl(url);
it should work. I have tried the same.

Android webview + progressbar: webview is re-shown before page is changed

I have the following problem with my Android app. I'm using a webview which has a progressbar. It works ok, but the problem is that when the progressbar is set to INVISIBLE again (on progress == 100), the webview hasn't changed pages yet (it does so shortly after reshowing).
In sum, it's this:
1. Webview in view
2. Webview to gone, progressbar to visible
3. Progressbar to gone, webview to visible
4. Webview actually changes the page
My goal is to have 4 happen before 3 (and thus not showing the webview before it has actually changed the page.
How can I do this?
My codes is as follows:
public class MyActivity extends Activity { WebView mWebView;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.loadUrl("http://www.myurl.com");
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == ProgressBar.GONE){
mWebView.setVisibility(WebView.GONE);
pd.setVisibility(ProgressBar.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100 && mWebView.getVisibility() == WebView.GONE) {
pd.setVisibility(ProgressBar.GONE);
mWebView.setVisibility(WebView.VISIBLE);
}
}
});
}
#Override
public void onBackPressed(){
if(mWebView.canGoBack())
mWebView.goBack();
else
super.onBackPressed();
}
}
class ClassWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
}
Layout:
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar
android:id="#+id/web_view_progress_bar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" >
</ProgressBar>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:visibility="visible">
</WebView>

How to add tabs dynamically that can be linked to a users choice of webpage

I am developing an application that uses tabs with each tab being linked to a webpage that the user will be able to see and interact with using webview. what i am having trouble with is implementing a add command that the user will be able to use to add a tab with a url of their choice that works just like the others
Below is my code
Here is the main java file that all other files use
public class UniversityofColorado extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost host=getTabHost();
host.addTab(host.newTabSpec("one")
.setIndicator("Google")
.setContent(new Intent(this, Hello.class)));
host.addTab(host.newTabSpec("two")
.setIndicator("Colorado Main Site")
.setContent(new Intent(this, ColoradoMainSiteBrowser.class)));
host.addTab(host.newTabSpec("three")
.setIndicator("CULearn")
.setContent(new Intent(this, CULearnBrowser.class)));
host.addTab(host.newTabSpec("four")
.setIndicator("CULink")
.setContent(new Intent(this, CULinkBrowser.class)));
host.addTab(host.newTabSpec("five")
.setIndicator("MyCUInfo")
.setContent(new Intent(this, MyCUInfoBrowser.class)));
host.addTab(host.newTabSpec("six")
.setIndicator("Campus Map")
.setContent(new Intent(this, CampusBrowser.class)));
host.addTab(host.newTabSpec("Seven")
.setIndicator("Notes")
.setContent(new Intent(this, Notepadv3.class)));
}
// Inflates menu when "menu Key" is pressed
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
}
Then i have each webpage defined in a seperate java file that the main file calls
below is one of them
public class ColoradoMainSiteBrowser extends Activity {
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://colorado.edu/");
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I have the menu defined in the main file i just need to construct the methods so the buttons do what they are suppose to do. any help would be great
Ok so I thought I've already answered to your question here
Besides, you seem to like to replicate similar questions here and here
Like I've already told you, you can acomplish this by creating an activity that accepts an url as an extra of an intent.
Taking your code as a base start:
Browser.java
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Browser extends Activity {
private WebView webview;
private String URL;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browser);
Bundle extras = getIntent().getExtras();
if (extras == null) {
URL = "http://www.evonytools.org/";
} else {
this.URL = extras.getString("URL");
}
getWebView();
}
public void getWebView() {
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(this.URL);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
layout/broswer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webview"
/>
</LinearLayout>
Main.java
public class Main extends TabActivity{
private TabHost tabHost;
private EditText addressBar;
private final static String DEFAULT_URL = "http://www.evonytools.org/";
private int z = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_main);
this.tabHost = getTabHost(); // The activity TabHost
this.addressBar = (EditText) findViewById(R.id.address_bar);
this.addressBar.setText(DEFAULT_URL);
ImageButton addBtn = (ImageButton) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addMethod();
}
});
Intent openBrowser = new Intent();
openBrowser.setClass(this, Browser.class);
openBrowser.putExtra("URL", DEFAULT_URL);
tabHost.addTab(tabHost.newTabSpec("Main").setIndicator(getHost(DEFAULT_URL)).setContent(openBrowser));
}
private void addMethod() {
String webSiteURL = validateURL(addressBar.getText().toString().trim());
String webSiteName = getHost(webSiteURL);
Intent openBrowser = new Intent();
openBrowser.setClass(this, Browser.class);
openBrowser.putExtra("URL", webSiteURL);
tabHost.addTab(tabHost.newTabSpec(webSiteName + Integer.toString(z)).setIndicator(webSiteName).setContent(openBrowser));
++z;
}
private void deleteMethod() {
// Since we can't really delete a TAB
// We hide it
int position = tabHost.getCurrentTab();
if (position != 0 ) {
tabHost.getCurrentTabView().setVisibility(8);
tabHost.setCurrentTab(0);
}
}
// Inflates menu when "menu Key" is pressed
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// This method is called once the menu is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
addMethod();
break;
case R.id.delete:
deleteMethod();
break;
}
return true;
}
private String validateURL(String url) {
StringBuffer urlB = new StringBuffer();
// checks if addressBar has a valid URL
// you can add stuff here in order to validate
// this is just an example
if (url.startsWith("http://")) {urlB.append(url);} else {urlB.append("http://");}
try {
URL urlTry = new URL(urlB.toString());
return urlB.toString();
} catch (MalformedURLException e) {
return "http://www.google.com/";
}
}
private String getHost(String url) {
try {
URL urlTry = new URL(url);
return urlTry.getHost().replace("www.", "").replace(".com", "").replace(".org", "").replace(".net", "");
} catch (MalformedURLException e) {
return "Browser";
}
}
}
tabs_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:tag="tabPane"
/>
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/address_bar"
android:layout_width="270px"
android:layout_height="50px"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
<ImageButton
android:id="#+id/add_btn"
android:layout_width="50px"
android:layout_height="50px"
android:src="#android:drawable/ic_menu_add"
android:background="#android:color/transparent"
android:layout_toRightOf="#id/address_bar"
/>
</RelativeLayout>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dp" />
</LinearLayout>
Hope I'm not doing your homework.

Categories

Resources