android setting default tab in tab-activity - android

android TabActivity launches the FragmentActivity associated with the first tab added in the sequence before setting tabhost.setCurretnTab(4);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_main);
try
{
DataSource.ObjContext = this.getApplicationContext();
DataSource.ObjTabBarActivity = this;
DataSource.ObjSharedPreferences = this.getSharedPreferences("com.example", Context.MODE_PRIVATE);
if(NetworkStat)
{
new LocationUpdates(this);
this.setTabs();
}
else
{
Log.d("in TabBarActivity", "Network failure");
Toast.makeText(this.getApplicationContext(), "Network failure", Toast.LENGTH_SHORT).show();
}
}
catch(Exception ex)
{
}
}
private void setTabs()
{
addTab("Clubs", R.drawable.tab_clubs, FragmentStackClubsActivity.class);
addTab("Events", R.drawable.tab_events, FragmentStackEventsActivity.class);
addTab("Rate", R.drawable.tab_rate, FragmentStackRateActivity.class);
addTab("Loyalty", R.drawable.tab_loyalty, FragmentStackLoyaltyActivity.class);
addTab("Setting", R.drawable.tab_settings, FragmentStackSettingsActivity.class);
if(DataSource.ObjSharedPreferences.getString(DataSource.LOGIN_TAG, "false").equalsIgnoreCase("false"))
{
getTabHost().setCurrentTab(4);
DataSource.disableTabBar();
}
else
{
}
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
but the problem is that it starts the first tab initially and then switches to 5th tab in this way a thread gets started from the first tab and that's what i don't want i.e if the user is not logged in i wanna redirect the user to login(settings) tab.
any help in this regard is highly appreciated......

public void setCurrentTab (int index)
public void setCurrentTabByTag (String tag)
you can like this
if (isNotLogin) {
tabHost.setCurrentTabByTag("Setting");
}
after addTab()
http://developer.android.com/reference/android/widget/TabHost.html#setCurrentTab(int)

Related

how to add the loading screen in to tab in android?

In my application i'm using two tabs one tab app contacts and other one is all contacts ,in application opening a one tab to other one it tack 10sce ,in that time how to add the same type of message like loading screen etc ,
plz tell me how to do that in my android app?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
final TabHost tabHost = getTabHost();
TextView txtTab = new TextView(this);
txtTab.setText("Mobell Contacts");
txtTab.setPadding(8, 9, 8, 9);
txtTab.setTextColor(Color.WHITE);
txtTab.setTextSize(14);
//txtTab.setTypeface(localTypeface1);
txtTab.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
TabHost.TabSpec spec;
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("tab1").setIndicator(txtTab).setContent(new Intent(this, ContactList.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
tabHost.addTab(spec);
TextView txtTab1 = new TextView(this);
txtTab1.setText("All Contacts");
txtTab1.setPadding(8, 9, 8, 9);
txtTab1.setTextColor(Color.WHITE);
txtTab1.setTextSize(14);
//txtTab.setTypeface(localTypeface1);
txtTab1.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
TabHost.TabSpec spec1;
// Initialize a TabSpec for each tab and add it to the TabHost
spec1 = tabHost.newTabSpec("Tab2").setIndicator(txtTab1).setContent(new Intent(this, TabAct2.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
tabHost.addTab(spec1);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#101010"));
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#848284"));
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#848284"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#181418"));
}
});
}
}
see this code plz tell how to add the progressDialog when tab change one to other...
You can do something like this for showing progress -
public class MainActivity extends Activity {
Button b;
ProgressBar pb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.button1);
pb1 = (ProgressBar)findViewById(R.id.progressBar1);
}
public void click(View v){
new Thread("thread1"){
public void run(){
try{
for(int i=0; i<10; i++)
{
Thread.sleep(4000);
pb1.setProgress(i*10);
}
}
catch(InterruptedException e){
e.printStackTrace();
}
};
}.start();
}
}
In case you want to show a message, use Spinner.
Show progressbar on center of screen using visibility on/off
Since you are using TabActivity (and you haven't posted your work around yet), so, I am guessing you have used
TabActivity
Activity (for both tabs)
Now, when you switch from one tab to another you are actually calling Activity. So, just create an AsyncTask in the Activity which takes time to load. For instance,
class ContactLoadAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute()
pd = ProgressDialog.show(YourActivity.this, "title", "loading", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// call your contact loading functions here
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
}
}
And, call this AsyncTask in onCreate() of your Activity.
new ContactLoadAsync().execute();

Animation between tabs while using intents as tabs, how can I do that?

I have a tabHost with 4 different intents in it. I am trying to see animation while traversing between tabs. the code I am using is partially works:
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
FrameLayout questionsLayout = (FrameLayout)tabHost.findViewById(android.R.id.tabcontent);
questionsLayout.setAnimation(AnimationUtils.loadAnimation(tabHost.getContext(), R.anim.go_left_in));
}
however it only animates one animation which is an "inAnimation", I also want to add an "outAnimation" too, how can I do that.
By the way, i am using this code to add each tabs:
intent = new Intent().setClass(this, Tabs.class);
intent.putExtra("questions", rawQ);
spec = tabHost.newTabSpec("english").setIndicator(getText(R.string.ingilizce),res.getDrawable(R.drawable.ic_tabs)).setContent(intent);
tabHost.addTab(spec);
Lastly, I am using api version 8.
Last edit, entire code:
public class Questions extends TabActivity implements OnTabChangeListener {
public static final String TAG = "Questions";
private String macAddr;
private String json;
private TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "Activity State: onCreate() " + TAG);
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
macAddr = extras.getString("macAddr");
json = extras.getString("json");
}
// Make it fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// parsing json data
Question[] rawQ = parseJson(json);
if (rawQ==null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Mac address could not found in database, please add it via control panel.")
.setCancelable(false)
.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent i = new Intent(Questions.this, AnrdoinActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
setContentView(R.layout.questions);
Resources res = getResources(); // Resource object to get Drawables
tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Tabs.class);
intent.putExtra("questions", getLanguageQuestions(rawQ, 1));
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost
.newTabSpec("kyrgyz")
.setIndicator(getText(R.string.kirgizca),
res.getDrawable(R.drawable.ic_tabs))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Tabs.class);
intent.putExtra("questions", getLanguageQuestions(rawQ, 2));
spec = tabHost
.newTabSpec("turkish")
.setIndicator(getText(R.string.turkce),
res.getDrawable(R.drawable.ic_tabs))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Tabs.class);
intent.putExtra("questions", getLanguageQuestions(rawQ, 3));
spec = tabHost
.newTabSpec("russian")
.setIndicator(getText(R.string.rusca),
res.getDrawable(R.drawable.ic_tabs))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Tabs.class);
intent.putExtra("questions", getLanguageQuestions(rawQ, 4));
spec = tabHost
.newTabSpec("english")
.setIndicator(getText(R.string.ingilizce),
res.getDrawable(R.drawable.ic_tabs))
.setContent(intent);
tabHost.addTab(spec);
Log.v(TAG, 0+"");
FrameLayout questionsLayout = (FrameLayout) tabHost.findViewById(android.R.id.tabcontent);
Log.v(TAG, 1+""+questionsLayout.getId());
Log.v(TAG, 2+"");
tabHost.setCurrentTab(0);
tabHost.setOnTabChangedListener(this);
}
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
FrameLayout questionsLayout = (FrameLayout) tabHost.findViewById(android.R.id.tabcontent);
questionsLayout.setAnimation(AnimationUtils.loadAnimation(tabHost.getContext(), R.anim.go_left_in));
}
// Database related elements
private Question[] parseJson(String text) {
JSONArray data = null;
JSONObject groups = null;
String[][] rawData = null;
JSONArray[] questions = null;
Question[] rawQ = null;
try {
data = new JSONArray(text);
questions = new JSONArray[data.length() - 1];
rawQ = new Question[questions.length];
groups = data.getJSONObject(0);
rawData = new String[2][groups.length()];
Iterator it = groups.keys();
int index = 0;
while (it.hasNext()) {
rawData[0][index] = (String) it.next();
rawData[1][index] = groups.getString(rawData[0][index]);
index++;
}
for (int i = 0; i < questions.length; i++) {
questions[i] = data.getJSONArray(i + 1);
String[] s = new String[6];
for (int j = 0; j < s.length; j++) {
s[j] = ((questions[i].getString(3 + j) == null) ? ("")
: (questions[i].getString(3 + j)));
}
rawQ[i] = new Question(questions[i].getInt(0),
questions[i].getInt(1), questions[i].getString(2), s);
}
Log.e(TAG, rawQ[1].getQuestion());
return rawQ;
} catch (JSONException e) {
Log.e(ACTIVITY_SERVICE, e.toString());
return null;
// ctv.setText(data.toString());
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
return null;
}
}
private Question[] getLanguageQuestions(Question[] Qs,int id){
int count=0;
for(Question q:Qs)
count+=((q.getLanguageId()==id)?(1):(0));
Question [] result = new Question[count];
int index=0;
for(Question q:Qs){
if(q.getLanguageId()==id){
result[index]=q;
index++;
}
}
return null;
}
}
I've been looking around for ages to try and implement this, and actually wound up getting animations between different tabs (where my tabs are separate activities) by extending the TabHost slightly. In this particular implementation I've separated the animations so that it animates differently if you're going to a tab to the left or right of the old one:
public class MyAnimTabHost extends TabHost {
public MyAnimTabHost(Context context) {
super(context);
}
public MyAnimTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setCurrentTab(int index) {
View currentView= this.getCurrentView();
if (this.getCurrentTab()< index){
if (currentView !=null){
currentView.startAnimation(AnimationUtils.loadAnimation(this.getContext(),R.anim.slide_out_to_left));
}
super.setCurrentTab(index);
currentView= this.getCurrentView();
if (currentView !=null){
currentView.startAnimation(AnimationUtils.loadAnimation(this.getContext(),R.anim.slide_in_from_right));
}
} else {
if (currentView !=null){
currentView.startAnimation(AnimationUtils.loadAnimation(this.getContext(),R.anim.slide_out_to_right));
}
super.setCurrentTab(index);
currentView= this.getCurrentView();
if (currentView !=null){
currentView.startAnimation(AnimationUtils.loadAnimation(this.getContext(),R.anim.slide_in_from_left));
}
}
}
}
Adding this as a new class, ADT will automatically add it to the list of custom views in the graphic xml editor, so you can just swap out the TabHost in the layout for this one, and all should be good (make sure you remember to actually implement your different anim xml files).
Don't use TabActivity et al they are deprecated as described in the documentation.
Use Fragment to do tabs. If you are targeting 3.0+, this is very straight-forward in combination with the action bar. If you want older style tabs, there are samples in ApiDemos showing how to use them with fragments such as FragmentTabs or Support Library Fragment Tabs.
Or use this with ViewPager such as Support Fragment Tabs Pager.

Want to exit the application on click of tab

I am making an application where i have set two bottom tabs,
namely "Exit" and "Back".
Now i want to exit from the application on the click of the "Exit" tab(not button).
How can i do that, i know that in android we can never actually close the application, but i want to go to the Home-screen on clicking "exit".
i have studied following link also along with other links
Is quitting an application frowned upon?
EDIT
public class Man_age_ur_PhoneActivity extends TabActivity {
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
setTabs();
}
private void setTabs()
{
addTab("Exit", R.drawable.tab_exit);
addTab("Back", R.drawable.tab_back);
//To add more tabs just use addTab() method here like previous line.
}
private void addTab(String labelId, int drawableId)
{
TabHost tabHost = getTabHost();
// Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
// spec.setContent(intent);
tabHost.addTab(spec);
}
}
on Click of your second tab , you just have to write "finish();". This will close previously opened activities and you can exit from your application.
you can use this code
public class Man_age_ur_PhoneActivity extends TabActivity {
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
setTabs();
getTabHost().setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
int i = getTabHost().getCurrentTab();
Log.i("######## ANN CLICK TAB NUMBER", "------" + i);
if (i == 0) {
Log.i("########## Inside onClick tab 0", "onClick tab");
}
else if (i ==1) {
Log.i("########## Inside onClick tab 1", "onClick tab");
}
}
});
}
private void setTabs()
{
addTab("Exit", R.drawable.tab_exit);
addTab("Back", R.drawable.tab_back);
//To add more tabs just use addTab() method here like previous line.
}
private void addTab(String labelId, int drawableId)
{
TabHost tabHost = getTabHost();
// Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
// spec.setContent(intent);
tabHost.addTab(spec);
}
}
Also import this
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
Taken from this link
Android TabWidget detect click on current tab
Generally Android apps shouldn't have an exit option, see for instance this post: http://blog.radioactiveyak.com/2010/05/when-to-include-exit-button-in-android.html
If you really want to, you can also just call System.exit(), this is guaranteed to close down the application completely.

Change tab host intent

I am working on an application that pulls information from the internet. The information is sorted into categories, sub-categories and, sub-sub-categories.
My main view is a TabHost view (the parent categories) with 3 tabs, and the initial list view (the sub-categories). When the user clicks an item in the list view it calls a new list view that displays the child-categories of the chosen sub-category.
I got everything to work except that when a sub category is chosen the tabHost view disappears and the sub-sub-categories are displayed in full screen.
How can I change the intent of the tab to display the child-categories of the sub-category?
EDIT: here is my code, sorry I didn't post it earlier!
My Main view which contains the tabhost:
public class tabwidget extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, category1Activity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("category1").setIndicator("Category1",
res.getDrawable(R.drawable.ic_tab_category1))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, category2Activity.class);
spec = tabHost.newTabSpec("category2").setIndicator("Category2",
res.getDrawable(R.drawable.ic_tab_category2))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, category3Activity.class);
spec = tabHost.newTabSpec("category3").setIndicator("Category3",
res.getDrawable(R.drawable.ic_tab_category3))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
When the application is started the alcohol tab is selected by default. This is the category1Acitivity listview with the onlclick action that calls the child-categories:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "You clicked item at position"+position,
//Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Loading "+((TextView) view.findViewById(R.id.categoryname)).getText(),
Toast.LENGTH_SHORT).show();
Intent i = new Intent(category1Activity.this, subCategoryActivity.class);
i.putExtra("id", ((TextView) view.findViewById(R.id.message)).getText());
i.putExtra("catname", ((TextView) view.findViewById(R.id.categoryname)).getText());
i.putExtra("parentcatid", "0");
startActivityForResult(i, ACTIVITY_CREATE);
}
});
The listviews are generated by the category Id which is sent to the server pulls results from the database.
You will have to use ActivityGroups to do that.
http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html
http://united-coders.com/nico-heid/use-android-activitygroup-within-tabhost-to-show-different-activity
However, keep in mind that ActivityGroups are deprecated in ICS.
EDIT: This is my implementation of ActivityGroup:
Activity in a tab:
Intent i = new Intent(v.getContext(), SearchList.class);
i.putExtra("search", search);
View view = SearchActivityGroup.group.getLocalActivityManager()
.startActivity("SearchList", i
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
SearchActivityGroup.group.replaceView(view);
ActivityGroup:
package nl.dante.SuperDeals;
import java.util.ArrayList;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SearchActivityGroup extends ActivityGroup {
View rootView;
// Keep this in a static variable to make it accessible for all the nested
// activities, lets them manipulate the view
public static SearchActivityGroup group;
// Need to keep track of the history if you want the back-button to work
// properly, don't use this if your activities requires a lot of memory.
private ArrayList<View> history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* this.history = new ArrayList<View>(); group = this;
*
* // Start the root activity within the group and get its view View
* view = getLocalActivityManager().startActivity("Search", new
* Intent(this,Search.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
* .getDecorView();
*
* // Replace the view of this ActivityGroup replaceView(view);
*/
}
#Override
protected void onResume() {
super.onResume();
this.history = new ArrayList<View>();
group = this;
// Start the root activity within the group and get its view
View view = getLocalActivityManager().startActivity("Search", new Intent(this, Search.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
// Replace the view of this ActivityGroup
replaceView(view);
}
public void replaceView(View v) {
// Adds the old one to history
if (history.size() == 0) {
if (rootView != null) {
history.add(rootView);
rootView = null;
}
}
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}
public void back() {
try {
if (history.size() > 0) {
if (history.size() == 1) {
rootView = history.get(0);
Toasts.ToastImageView(this, "Druk nogmaals BACK om af te sluiten", R.drawable.power_64_off, "red");
}
history.remove(history.size() - 1);
setContentView(history.get(history.size() - 1));
} else {
finish();
}
if (history.size() < 3) {
// Tabhost.bannerImage2.setImageResource(0);
Tabhost.banner.setBackgroundResource(R.drawable.gradient_blue);
}
if (history.size() == 2) {
Tabhost.bannerImage1.setImageResource(R.drawable.sorteer_btn);
}
} catch (Exception ex) {
}
}
public int getHistorySize() {
return history.size();
}
#Override
public void onBackPressed() {
try {
SearchActivityGroup.group.back();
} catch (Exception ex) {
}
return;
}
}

Switching between tab using activity group it want to display last activity - Tab ActivityGroup

I have written tab for my android application.
My question is switching between tab using activity group it want to display last activity. I want to show last open/visited screen when we navigate the tab.My one is go to first screen:
I need to show last opened screen when navigate through Tab
Tab 1 -> Sales. This contain 10 screen inside (actiivity)
Tab 2 -> Admin .This contain 5 screen inside (actiivity)
Tab 3 -> Setting.This contain 8 screen inside. (actiivity)
I clicked Tab 1 , it load tab 1's screen which is contain list of sales route .then I clicked one sales route , it goes to list of retailer in the first tab.Then I cliched tab 3 "Setting " finish some work & come back to sales, That time it should show last open screen in the "sales" tab.
When I clicked tab, It should show last open activity How to do?
I did like this.Please indicate where I want to change the code for my requirements.
MainActivity.It will call after login
public class MainActivity extends TabActivity {
int selectedTab;
TabHost tabHost ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
TabHost t = getTabHost();
tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");
/** TabSpec setIndicator() is used to set name for the tab. */
/** TabSpec setContent() is used to set content for a particular tab. */
firstTabSpec.setIndicator("Sales").setContent(new Intent(this,SalesActivityGroup.class));
secondTabSpec.setIndicator("Admin").setContent(new Intent(this,SettingActivityGroup.class));
thirdTabSpec.setIndicator("Setting").setContent(new Intent(this,SettingActivityGroup.class));
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
tabHost.addTab(thirdTabSpec);
tabHost.setCurrentTab(0);
tabHost.setMinimumHeight(25);
}
public void onTabChanged(String arg0) {
selectedTab = tabHost.getCurrentTab();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
First Tab1(Sales)'s SalesGroupActivity
public class SalesActivityGroup extends ActivityGroup {
public static SalesActivityGroup group;
private ArrayList<View> history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
View view = getLocalActivityManager().startActivity("Sales",
new Intent(this, SalesRouteActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
}
public void replaceView(View v) {
history.add(v);
setContentView(v);
}
public void back() {
if (history.size() > 0) {
history.remove(history.size() - 1);
if (history.size() > 0) {
setContentView(history.get(history.size() - 1));
} else {
finish();
}
} else {
finish();
}
}
#Override
public void onBackPressed() {
SalesActivityGroup.group.back();
return;
}
Edited
This is FirstTab's firstActivity - SalesRouteActivity
public class SalesRouteActivity extends ListActivity{
TableLayout tl;
static int positions = 0;
static String keyword ="";
int uploadSize = 0;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
String strBusinessUnit = "";
String strExecutive = "";
String strTerritoryCode = "";
SimpleAdapter sd;
View row = null;
View selectRow = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sales_routes);
SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_WORLD_READABLE);
strBusinessUnit = myPrefs.getString("BusinessUnit", "");
strExecutive = myPrefs.getString("Executive", "");
strTerritoryCode = myPrefs.getString("TerritoryCode", "");
ArrayList<SalesRoutes> routeList = getSalesRoute();
ArrayList<HashMap<String, String>> routhPath = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < routeList.size(); i++) {
if(Integer.parseInt(routeList.get(i).getOutlets()) >0){
HashMap<String, String> map = new HashMap<String, String>();
map.put("routeCode",((SalesRoutes) routeList.get(i)).getRouteCode());
map.put("routeName",((SalesRoutes) routeList.get(i)).getDescription());
map.put("outlets", ((SalesRoutes) routeList.get(i)).getOutlets());
routhPath.add(map);
}
}
ListView list = getListView();
sd = new SimpleAdapter(this, routhPath, R.layout.route_path,new String[] {"routeCode","routeName","outlets" },new int[] { R.id.routeCode,R.id.routeName,R.id.outlets});
row = getLayoutInflater().inflate(R.layout.route_path_row, null, false);
getListView().addHeaderView(row);
list.setAdapter(sd);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelected(true);
list.setTextFilterEnabled(true);
list.setItemsCanFocus(true);
list.setItemChecked(positions, true);
list.setSelectionAfterHeaderView();
if (routeList.size() > 0) {
keyword = routeList.get(0).getRouteCode();
}
uploadSize = new UploadActivity().getUploadTable();
if (uploadSize > 0) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(R.drawable.icon, "New Alert, Click Me!",System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "Upload Available...";
CharSequence contentText = "Browse Android Official Site by clicking me";
Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
PendingIntent intent = PendingIntent.getActivity(SalesRouteActivity.this, 0, notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle,contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
}
#SuppressWarnings("unchecked")
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
HashMap<String, String> hashMap = (HashMap<String, String>) l.getItemAtPosition(position);
keyword = hashMap.get("routeCode");
positions = position;
if(position == 0 ){
}else if(position != 1){
Intent showContent = new Intent(v.getContext(),SalesRouteDevitionActivity.class);
Bundle bundle = new Bundle();
bundle.putString("RouteCode", keyword);
showContent.putExtras(bundle);
getParent().startActivityForResult(showContent, 5);
}else{
Intent intent = new Intent(SalesRouteActivity.this, ListRetailerActivity.class);
Bundle bundle = new Bundle();
bundle.putString("RouteName", keyword);
intent.putExtras(bundle);
View view = SalesActivityGroup.group.getLocalActivityManager().startActivity("", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
SalesActivityGroup.group.replaceView(view);
}
}
#Override
public void onBackPressed() {
SalesActivityGroup.group.back();
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList<SalesRoutes> getSalesRoute(){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String sql = "SELECT RouteCode, Description, OutletsAttached " +
"FROM WMRoute " +
"WHERE ActiveStatus = '1' AND RouteDefaultExecutive = ? AND BusinessUnit = ? AND TerritoryCode = ? " +
"ORDER BY RouteCode ";
String[]d = new String[]{strExecutive,strBusinessUnit,strTerritoryCode};
ArrayList stringList = dbAdapter.selectRecordsFromDBList(sql, d);
dbAdapter.close();
ArrayList<SalesRoutes> salesRoutesList = new ArrayList<SalesRoutes>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<Object> arrayList = (ArrayList<Object>) stringList.get(i);
ArrayList<Object> list = arrayList;
SalesRoutes salesRoutes = new SalesRoutes();
try {
salesRoutes.setRouteCode((String) list.get(0));
salesRoutes.setDescription((String) list.get(1));
salesRoutes.setOutlets((String)list.get(2));
} catch (Exception e) {
Log.i("***" + SalesRouteActivity.class.toString(), e.getMessage());
}
salesRoutesList.add(salesRoutes);
}
return salesRoutesList;
}
}
probably my ActivityGroups are being created again and again when you switch between tabs
So groups want to create only once and resumed when i switch between tabs
Every screen details/contents getting from database..
I am facing this issue more than 2 days....Please help me.
Please help me on this....
Thanks in advance.....
I think you have to override onBackPressed() inside activities which you are opening in activity-group
Write a code below in each activity which you are opening in activity-group
#Override
public void onBackPressed() {
SalesActivityGroup.group.back();
}
And also replace the onBackPressed() with following code in TABHOST
#Override
public void onBackPressed() {
super.onBackPressed();
}
Best of luck
The activity groups you created will hold your current activity view will not change unless you change it, Therefore while you are navigating between tabs the activity groups you have assigned to those tabs will not change their views will remain as it is.
You can try this ....
For each of your activity you must override onBackPressed() ...
#Override
public void onBackPressed() {
ActivityGroupRelatedToThisActivity.group.back();
}
Also remember do not call super.onBackPressed() in any of your Activity which is related to activity group
Or
Change private ArrayList<View> history to static private ArrayList<View> history
and
if(history.size() == 0) replaceView(view);
in ActivityGroup's onCreate() method
This answer will be help you. I have used the group activity for my tabs. Let me know if you still find the problem
Why Back button is not detecting in muti tab activities?
I think you are having a problem in back() of ActivityGroup, please try this.
public void back()
{
if ( history.size() > 1 )
{
history.remove(history.size() - 1);
View v = arrList.get(history.size() - 1);
setContentView(v);
}
else {
this.finish();
}
}
Thanks All;
There were issue in my MainActivity.
tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, SalesActivityGroup.class);
spec = getTabHost().newTabSpec("Sales").setIndicator("Sales",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SettingActivityGroup.class);
spec = getTabHost().newTabSpec("Admin").setIndicator("Admin",getResources().getDrawable(R.drawable.admin)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SettingActivityGroup.class);
spec = getTabHost().newTabSpec("Setting").setIndicator("Setting",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SettingActivityGroup.class);
spec = getTabHost().newTabSpec("Inquiry").setIndicator("Inquiry",getResources().getDrawable(R.drawable.ic_tab_artists_grey)).setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
tabHost.setMinimumHeight(18);
tabHost.setFadingEdgeLength(5);
tabHost.setFocusable(true);
tabHost.requestFocus();
tabHost.setFadingEdgeLength(5);
}
}
And I agree #Vaibhav Jani #Dharmendra #Suri, I missed that onKeyPressed() in all Activity.
I saw your update. I'm not sure how to answer your question. Perhaps you can save information about what view is currently being diplayed in onSavedInstanceState and fetch the data it in onRestoreInstancestate and use it to recreate the view. As a side note, ActivityGroup is deprecated, and has been replaced by the Fragment API.

Categories

Resources