Select Item on Spinner - java

I want to ask for help.
I already created a list of activities in Android Studio.
Each Activity contains a specific item. Those items are different "Departments" in our University.
Example:
Activity 1 = College of Computer Studies;
Activity 2 = College of Teacher Education;
Activity 3 = College of Engineering.
My Spinner contains the departments.
My problem is, if I choose "College in Computer Science" in Spinner and click the "SEND" button, I want Activity 1 to be shown.
Would you help me with the code to do that?
**Spinner in activity_main.xml
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:entries="#array/punpDepartments"
android:layout_gravity="center_vertical">
</Spinner>
**These are the items in strings.xml
<string-array name="punpDepartments">
<item>College of Computer Studies</item>
<item>College of Business Education</item>
<item>College of Criminal Justice Education</item>
<item>College of Marine Education</item>
<item>College of Nursing</item>
<item>College of Pharmacy</item>
<item>College of Education</item>
**My code in Intent at MainActivity.java
public class MainActivity extends ActionBarActivity {
private static Button button_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickButtonListener();
}
public void OnClickButtonListener(){
button_send = (Button) findViewById(R.id.button);
button_send.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent("com.example.imelda.mythesis.ListActivity");
startActivity(intent);
}
}
);
}
**Extends in ListActivity.java
public class ListActivity extends ActionBarActivity {
private static Button button_next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
OnClickButtonListener();
}
#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_list, menu);
return true;
}
public void OnClickButtonListener() {
button_next = (Button) findViewById(R.id.button4);
button_next.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.imelda.mythesis.SecondList");
startActivity(intent);
}
}
);
}
**I have also added this in AndroidManifest.xml enter code here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imelda.mythesis" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ListActivity"
android:label="#string/title_activity_list" >
<intent-filter>
<action android:name="com.example.imelda.mythesis.ListActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>

first get your spinner in the main class like this
Spinner spin =(Spinner)findViewById(R.id.spin);
now in your on click method do this
int position =spin.getSelectedItemPosition();
//change the activities with yours
switch (position){
case 0: intent.setClass(Activity1.class,MainActivity.this);
break;
case 1: intent.setClass(Activity2.class,MainActivity.this);
break;
case 2: intent.setClass(Activity3.class,MainActivity.this);
break;
case 3: intent.setClass(Activity4.class,MainActivity.this);
break;
case 4: intent.setClass(Activity5.class,MainActivity.this);
break;
}
startActivity(intent);

Related

Context for onOptionsItemSelected in app-wide menu

This app has just two activities. MainActivity was renamed to SpecialsActivity. The other activity is PizzaActivity. Using the BottomNavigationView, I want to navigate between the two activities. So far, the app opens in SpecialsActivity, and the pizza button does open the PizzaActivity. But then it will not switch back to the SpecialsActivity. I think the issue is related to context. Please help.
SpecialsActivity.java
public class SpecialsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_specials);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_specials:
Intent specials_intent = new Intent(this, SpecialsActivity.class);
startActivity(specials_intent);
return true;
case R.id.action_pizza:
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
startActivity(pizza_intent);
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
}
activity_specials.xml
<android.support.design.widget.BottomNavigationView
android:layout_width="0dp"
android:layout_height="49dp"
app:itemBackground="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu" />
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".SpecialsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PizzaActivity"></activity>
</application>
bottom_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_specials"
android:icon="#drawable/ic_home_black_24dp"
android:title="Specials"
app:showAsAction="always"
android:onClick="onOptionsItemSelected" />
<item
android:id="#+id/action_pizza"
android:enabled="true"
android:icon="#drawable/ic_local_pizza_black_24dp"
android:title="Pizza"
app:showAsAction="always"
android:onClick="onOptionsItemSelected"/>
</menu>
Try changing
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
into this
Intent pizza_intent = new Intent(this, PizzaActivity.class);

Run Time Main Activity not come after Splash Activity and app close

Everything in my code looks good in both the .java and .xml files (according to the software) because I have no errors yet every time I click the app icon in the emulator, it brings up the splash screen then the app exits without showing my main activity. Here's my code so far:
SplashActivity.java
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hide title bar of activity
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//Making activity full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
int t =3000; //time for spash screen 3000 means 3sec
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
},t);
}
}
SplashActivity.xml
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:src="#drawable/icon"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity.java:
public class MainActivity extends AppCompatActivity
{
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = (WebView) findViewById(R.id.webView);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView.setWebViewClient(new HelpClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
setTitle("Loading..."); //when url is loading set this on actionbar
if (newProgress == 100) {
frameLayout.setVisibility(View.GONE); // Hide progress bar when page is loaded
setTitle(view.getTitle()); //get amd set title of opend page
}
super.onProgressChanged(view, newProgress);
}
});
webView.getSettings().setJavaScriptEnabled(true); //enable javaScript
//check internet connection
if (haveNetworkConnection()) {
webView.loadUrl(webAdress);
} else {
Toast.makeText(this, "No internet Connection", Toast.LENGTH_SHORT).show();
}
progressBar.setProgress(0);
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(View.VISIBLE);
return true;
}
}
private boolean haveNetworkConnection(){
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for(NetworkInfo ni : networkInfos){
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//check if the event was the back button and if there's history
if ((keyCode==KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
//if it was the back or there is no web page history, bubble up to the default system behaviour
return super.onKeyDown(keyCode, event);
}
}
MainActivity.xml:
<!--Progressbar-->
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="3dip"
android:background="#android:color/transparent">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="match_parent"
style="?android:attr/progressBarStyleHorizontal"
android:layout_height="7dp"
android:layout_gravity="top"
android:layout_marginTop="-3dp"
android:progressDrawable="#drawable/custom_progress"
android:background="#android:color/transparent"
android:progress="20"/>
</FrameLayout>
<!--WebView-->
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</WebView>
Here's my manifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--internet permision-->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity">
</activity>
</application>
Any hints would be greatly appreciated, thank you!
The problem is in onCreate method of MainActivity, you do not provide any UI (xml layout file), as a result, the app cannot find view elements to init, set listeners, etc. I guess you can find an exception in logcat when your app close.
Solution: Provide a layout xml file for MainActivity
public class MainActivity extends AppCompatActivity {
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Add this line
webView = (WebView) findViewById(R.id.webView);
...
}
}
try use
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Your code is not so good. If you want to show splashscreen only when app start I recommend using the following code:
AndroidManifest.xml
<activity android:name=".view_layer.activities.SplashScreenActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
styles.xml
<style name="SplashTheme" parent="#android:style/Theme.NoTitleBar.Fullscreen">
<item name="android:windowBackground">#drawable/splash</item>
</style>
SplashscreenActivity.java
public class SplashscreenActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
More: https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565

Android Up button quitting application instead of going to parent

So in my app, when I press the up button, the activity quits instead of going to its parent Activity. What might be wrong here?
SettingsActivity.java:
public class SettingsActivity extends AppCompatPreferenceActivity {
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
LinearLayout content = (LinearLayout) root.getChildAt(0);
LinearLayout toolbarContainer = (LinearLayout) View.inflate(this, R.layout.activity_settings, null);
root.removeAllViews();
toolbarContainer.addView(content);
root.addView(toolbarContainer);
mToolbar = (Toolbar) toolbarContainer.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
addPreferencesFromResource(R.xml.pref_general);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
}
How this activity is called:
private void openSettingsActivity() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}
And the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.bluecover.wearable3d"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="23" />
<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/female_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".DrawerActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"
android:parentActivityName=".DrawerActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="pt.bluecover.wearable3d.DrawerActivity" />
</activity>
</application>
</manifest>
So, What might be wrong with this behavior?
Add this in your SettingsActivity
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(menuItem);
}
Don't forget to override onBackPressed and call super.onBackPressed();
#Override
public void onBackPressed() {
super.onBackPressed();
}
try this code
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
//NavUtils.navigateUpFromSameTask(this);
finish();
}

icon not displayed on actionbar

I was going through the tutorial by google and couldn't figure out how to place search icon on action bar.
this is the main_activity_actions.xml code :-
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
this is the MainActivity.java :-
public class MainActivity extends ActionBarActivity
{
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void openSearch()
{
}
public void openSettings()
{
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:theme="#style/Theme.AppCompat.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.example.myfirstapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
</manifest>
I have already seen few answers and posted an the stack overflow and tried them and it still doesn't work
the search icon never shows up while I try to run it
can someone suggest what to do?
in activity_action.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:(YOUR_PROJECT_NAME)="http://schemas.android.com/apk/res-auto"
>
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
YOUR_PROJECT_NAME:showAsAction="always" />

set the tabbar bottom on android all activities

i have develop one android application.
Here i have to set the tabbar bottom on all android activities.how can i do.please give me solution for these.
i have totally 10 activities means the tabbar is show on botton on all 10 activities.how can i do in android.please help me.
These is my 1st activity:
setContentView(R.layout.tabbar);
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
TabSpec dbspec = tabHost.newTabSpec("Home");
dbspec.setIndicator("Home", getResources().getDrawable(R.drawable.home));
Intent dbIntent = new Intent(this, MainActivity.class);
dbspec.setContent(dbIntent);
tabHost.addTab(dbspec);
TabSpec orderspec = tabHost.newTabSpec("Cart");
orderspec.setIndicator("Cart", getResources().getDrawable(R.drawable.cart));
Intent orderIntent = new Intent(this, ViewCartActivity.class);
orderspec.setContent(orderIntent);
tabHost.addTab(orderspec);
TabSpec settingspec = tabHost.newTabSpec("My Account");
settingspec.setIndicator("My Account", getResources().getDrawable(R.drawable.myaccount));
Intent settingIntent = new Intent(this, CustomerLogin.class);
settingspec.setContent(settingIntent);
tabHost.addTab(settingspec);
tabbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/linearLayout1"
android:layout_height="match_parent">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs"
android:layout_alignParentBottom="true">
</TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
</FrameLayout>
</RelativeLayout>
</TabHost>
In first tab have to perform MainActivity(GridView) activity.it is woked well.in Main activity i have to clik any item means it is go to SubCate(listview) activity.Here also i have to display tabbar on bottom.how can i set.
In subcate.xml file have included below code:
<include
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
layout="#layout/tabbar" />
but the tabbar is not display.whats wrong here.please help me.
Please write below code instead of your code for add multiple activities in one TabActivity, it will solve your problem.
ActivityStack.java
public class ActivityStack extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null)
stack = new Stack<String>();
// start default activity
push("FirstStackActivity", new Intent(this, Tab_SampleActivity.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1)
finish();
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
TabActivity.java
public class TabActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.home));
spec.setContent(intent);
tabHost.addTab(spec);
Intent intent1 = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.invoice));
spec1.setContent(intent1);
tabHost.addTab(spec1);
tabHost.setCurrentTab(0);
}
}
FirstActivity.java
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Tab Sample Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondActivity", intent);
}
});
setContentView(textView);
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdActivity", intent);
}
});
setContentView(textView);
}
}
ThirdActivity.java
public class ThirdActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Add Below XML files into your res/layout folder.
1) tab_screen.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" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="3dp" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#android:id/tabs"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</TabHost>
2) main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
AndroidManifest.xml:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.tabsample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".TabActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ActivityStack"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ThirdActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
And see below link for more information on add multiple activities under one TabActivity with complete example.
Android - Multiple Android Activities under one TabActivity
You can use this class for implementing the functionality you have specified.
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
public class TabActivityGroup extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
#Override
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
current.finish();
}
}
}
Create an intermediate activity as below by extending TabActivitygroup
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class InterMediateActivity extends TabActivityGroup{
String TabID;
String TabName;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TabID=getIntent().getStringExtra("TabID");
TabName=getIntent().getStringExtra("TabName");
Log.i("Tab from intermediate",""+TabID+" "+TabName);
filterTabs(TabID);
}
private void filterTabs(String TabID)
{
if(TabID.trim().equals("Home"))
{
startChildActivity("Options", new Intent(this,HomePage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Menu"))
{
startChildActivity("Options", new Intent(this,MenuPage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Gallery"))
{
Log.i("GALLERY check", "gallery check");
startChildActivity("Options", new Intent(this,GalleryPage.class));
}
if(TabID.trim().equals("Aboutus"))
{
startChildActivity("Options", new Intent(this,AboutUsPage.class));
}
if(TabID.trim().equals("Location"))
{
startChildActivity("Options", new Intent(this,LocationList.class));
}
if(TabID.trim().equals("Events"))
{
startChildActivity("Options", new Intent(this,EventsPage.class));
}
if(TabID.trim().equals("TipCalculator"))
{
startChildActivity("Options", new Intent(this,TipCalculatorPage.class));
}
if(TabID.trim().equals("Special"))
{
startChildActivity("Options", new Intent(this,SpecialPage.class));
}
if(TabID.trim().equals("NowRunning"))
{
startChildActivity("Options", new Intent(this,NowRunningPage.class));
}
if(TabID.trim().equals("ShowTimes"))
{
startChildActivity("Options", new Intent(this,ShowTimePage.class));
}
if(TabID.trim().equals("GpsCoupon"))
{
startChildActivity("Options", new Intent(this,GPSCouponPage.class));
}
if(TabID.trim().equals("UpcomingMovieNames"))
{
startChildActivity("Options", new Intent(this,UpcomingPage.class));
}
if(TabID.trim().equals("PriceListOfServices"))
{
startChildActivity("Options", new Intent(this,ServicesPage.class));
}
if(TabID.trim().trim().equals("NewsLetter"))
{
Log.i("newsletter check", "newsletter check");
startChildActivity("Options", new Intent(this,NewsLetter.class));
}
if(TabID.trim().trim().equals("Website"))
{
startChildActivity("Options", new Intent(this,WebSitePage.class));
}
}
}
And instead of setting the tabs from tabactivity directly you can set them inside the intermediate activity. Then call the Intermediate activity from the tabactivity.
Intent intent = new Intent(this, InterMediateActivity.class);
intent.putExtra("TabID", item.elementAt(0));
intent.putExtra("TabName", item.elementAt(1));

Categories