Friday, April 22, 2011

Adding Tabs dynamically in Android


Step 1: Create a xml name tabhost.xml, for desigining the Tab Host, as i shown below
<?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>
</TabHost>



Step 2:  Create a Activity which extends TabActitvity as i shown below


public class Main extends TabActivity{

private TabHost tabHost;
private EditText addressBar;
  private final static String DEFAULT_URL = "http://www.google.com/";
private int z = 0;
private String SanTest=null;

/** 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();  // Method which adds the Tab Host
}
});
Intent openBrowser = new Intent();
openBrowser.setClass(Main.this, Browser1.class);
openBrowser.putExtra("URL", DEFAULT_URL);
SanTest=Intent.CATEGORY_LAUNCHER;
Log.d("SanTest",SanTest);
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, Browser1.class);
openBrowser.putExtra("URL", webSiteURL);

tabHost.addTab(tabHost.newTabSpec(webSiteName + Integer.toString(z)).setIndicator(webSiteName).setContent(openBrowser));
Log.d("z",Integer.toString(z));
++z;

}

private void deleteMethod() {

// Since we can't really delete a TAB
// We hide it

int position = tabHost.getCurrentTab();
Log.d("Position",Integer.toString(position));


// if (position != 0 ) {
//
// tabHost.getCurrentTabView().setVisibility(1);
// tabHost.setCurrentTab(position-1);
//
// }
// else if(position== z){
// tabHost.getCurrentTabView().setVisibility(1);
// tabHost.setCurrentTab(position+1);
// }
Log.d("Z val in delete()",Integer.toString(z));
if(position >0)
{
tabHost.getCurrentTabView().setVisibility(View.GONE);
tabHost.setCurrentTab(position+1);
z-=1;
if(z<0)
z=0;
}
else if(position == 0)
{
tabHost.getCurrentTabView().setVisibility(View.GONE);
tabHost.setCurrentTab(position+1);
z=0;
}
else if(position == z)
{
tabHost.getCurrentTabView().setVisibility(View.GONE);
tabHost.setCurrentTab(z-1);
Log.d("Z value in final","lol");
Log.d("Pos",Integer.toString(position));
Log.d("z pos",Integer.toString(z));


}


}

// Inflates menu when "menu Key" is pressed
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.title_icon, 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";
}
}

}
 
Step 3:  Inside an XML , which will display the Web View

<?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>

Step 4:  Create the Activity which load the url in WebView

public class Browser1 extends Activity {

private WebView webview;

private String URL;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.broswer);
webview = (WebView) findViewById(R.id.webview);

Bundle extras = getIntent().getExtras();
Log.d("I m before If","1");
if (extras == null) {
Log.d("I m in if condition","1");
URL = "http://www.google.org/";

} else {
Log.d("I m in else condition","2");
this.URL = extras.getString("URL");
Log.d("URL",this.URL);
}

getWebView();

}

public void getWebView() {
//Log.d("GetWebView Invoked", URL);
webview.loadUrl(URL);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);

}

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);
}

}

 Step 5:  Output Screen Shot







2 comments:

  1. Hi Sankar,
    The post is pretty useful, all postings are very unique. The application Dynamic tab adding and deleting is getting crashed, when i try to launch it. I am not able to resolve it. Could you please help by posting the files somewhere.. or to my email id vinod.marangappanavar@gmail.com?

    Thanks a lot

    Best Regards
    Vinod

    ReplyDelete
  2. Hello VinodKumar,

    can you pls check your Logcat and convey me what error message you are getting at the time of crashing ? so that i can help you.

    Thanks

    Sankar Ganesh.S

    ReplyDelete

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...