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.
Related
I have a simple Webview app that opened (HTML internet links) I added I single Button at the Top of the webView but can figure out how to link it. When a user taps the button, it should skip all history and go back to the home page activity main that contains the loaded HTML.
I have added this to the MainActivity.java but no luck.. please I need your help.. help change the codes below to what they should be... Java.. activity .. and possible Manifest
/******** home button back to activity_main when user tap Select Source ********/
public void gotoactivity_main(View view) {
Intent intent = new Intent(this, activity_main.class);
startActivity(intent);
}
private Object gotoactivity_main() {
return webView.canGoBack();
}
public void startActivity(Intent intent) {
}
/**END of Home button back to activity_main when user tap Select Source ***/
================================================================
Activity_main.xml=================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/home_button"
android:icon="#drawable/home"
android:layout_width="match_parent"
android:layout_height="38dp"
android:text=" Select Source"
android:onClick="gotoactivity_main"/>
<WebView
android:id="#+id/myWebView"
android:layout_width="match_parent"
android:layout_height="690dp">
</WebView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.myWebView);
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new Callback());
webView.loadUrl("file:///android_asset/index.html");
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
}
/**
* home button back to activity_main when user tap Select Source
***/
public void gotoactivity_main(View view) {
Intent intent = new Intent(this, activity_main.class);
startActivity(intent);
}
private Object gotoactivity_main() {
return webView.canGoBack();
}
public void startActivity(Intent intent) {
}
/**
* END of Home button back to activity_main when user tap Select Source
***/
#Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private class activity_main {
}
}
I have written sample webview code by looking at examples found from internet. I want to show progressbar till webview loads a page in my fragment.
My activity contains toolbar, frame that shows fragments and navigation drawer. When i select an entry from navigation drawer, new fragment is shown which contains progress bar and webview and the fragment simply tries to load the page below is the code for fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_full_page, container, false);
//int view_num = getArguments().getInt(ARG_SECTION_NUMBER);
progressBar = (ProgressBar)rootView.findViewById(R.id.webviewProgress);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) rootView.findViewById(R.id.webView1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String urlString = getArguments().getString("URLSTRING");
final Boolean clickable = getArguments().getBoolean("CLICKABLE");
Boolean networkAvailable = Utils.isNetworkAvailable(super.getActivity().getApplicationContext());
if(networkAvailable == true) {
webView.loadUrl(urlString);
} else {
webView.loadUrl(Utils.DEFAULT_URL_PAGE);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//progressBar.setVisibility(View.VISIBLE);
if (clickable) {
view.loadUrl(url);
return false;
} else {
return true;
}
}
#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);
}
});
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
Below is fragment_full_page.xml
<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=".FragmentFullPage" >
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center|top"
android:id="#+id/webviewProgress"
/>
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
web page is taking time to load (tried with wifi and 3g) but progress bar is not showing any time.
To test if progressbar actually shows in the middle of the fragment_full_page, I removed webview code and just kept progress bar then it is showing.
made something wrong with the code that is not showing progress bar while webview is loading which i am unable to figure out.
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>
Hello i have a weird thing here, i have a list of items and i want when i click on any item, it will open an WebView which looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:theme="#android:style/Theme.Dialog">
<WebView android:id="#+id/BrowserView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
here is the code i invoke the WebView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
setContentView(R.layout.external_view);
// load url or html
RssItem listItem = (RssItem) listView.getItemAtPosition(position);
webView = (WebView) findViewById(R.id.BrowserView);
// set browser settings
webView.setWebViewClient(new ExternalWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.setInitialScale(1);
try {
webView.loadUrl(listItem.getExternalUrl());
} catch (Exception ex) {
Log.d("WEBVIEW", ex.getMessage());
}
}
});
Here is the "ExternalWebViewClient" class
public class ExternalWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
view.clearHistory();
}
}
Now the question:
How do i close it and stay in the same activity after i press the "back" button,
here is my back button handling code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack() == true) {
webView.goBack();
} else {
//what should i do here?????????????????
return true;
}
}
}
return false;
}
Basically, you should not need to handle Back button yourself. If you are in the WebView and press Back - you should be taken to your last activity by default.
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.