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;
}
}
Related
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.
I have issue with ActivityGroup. My app has 4 tabs, 2 of which has ActivityGroup and 2 more simple activity. The problem is that after first run of app content is shown properly, and when leave app through back button and return, tabs with activity group dont shown any content, including menus. While tabs with simple activity work properly.
D'you have any ideas?
Ok, some sort of code)
Setting this tab:
private TabSpec getFrontPageTab() {
Intent intent = new Intent(context, ActivityGroupHome.class);
return tabHost
.newTabSpec("home")
.setIndicator(
getTabView(R.drawable.tabbar_home, "str_home"))
.setContent(intent);
}
ActivityGroupHome:
public class ActivityGroupHome extends ActivityGroupBase {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ActivityUtils activityUtils = ActivityUtils.getInstance(this);
activityUtils.addActivityGroup("Home", this);
activityUtils.startHomeActivity("Home");
}
}
Methods from ActivityUtils:
public void startHomeActivity(String activityGroupName) {
if (activityGroupName != null) {
startHomeActivityForActivityGroup(activityGroupName);
} else {
Intent intent = new Intent(context, AsyncMainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
private void startHomeActivityForActivityGroup(String activityGroupName) {
ActivityGroupListItem activityGroupItem = activityGroups
.findGroupByName(activityGroupName);
if (activityGroupItem != null) {
Intent intent = new Intent(activityGroupItem.activityGroup,
AsyncMainActivity.class);
intent.putExtra(ACTIVITY_GROUP_NAME, activityGroupItem.name);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
View view = activityGroupItem.activityGroup
.getLocalActivityManager().startActivity("Home", intent)
.getDecorView();
activityGroupItem.activityGroup.setContentView(view);
activityGroupItem.stack.add("Home");
}
}
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.
I have a TabActivity with 4 tabs. When clicking on a button within one of the tabs and starting a new Activity (a new Activity not within the TabHost), the new Activity does not register OnClick(). The new Activity can't even show a Toast wich makes me think the TabHost is somehow blocking the ui?
When putting the Activity as one of the Tabs the OnClick works just fine.
Any ideas what the reason for this is?
I've included 3 classes:
1) The TabActivity
2) The Activity in a tab that starts:
3) The new Activity that cannot register OnClick()
1) TabActivity:
public class OverView extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
/** TabHost will have Tabs */
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
/** TabSpec used to create a new tab.
* By using TabSpec only we can able to setContent to the tab.
* By using TabSpec setIndicator() we can set name to tab. */
/** tid1 is firstTabSpec Id. Its used to access outside. */
TabSpec Search = tabHost.newTabSpec("tid1");
TabSpec AllArtists = tabHost.newTabSpec("tid1");
TabSpec Favorites = tabHost.newTabSpec("tid1");
TabSpec About = tabHost.newTabSpec("tid1");
/** TabSpec setIndicator() is used to set name for the tab. */
Search. setIndicator("Search");
AllArtists. setIndicator("AllArtists");
Favorites. setIndicator("Favorites");
About. setIndicator("About");
/** TabSpec setContent() is used to set content for a particular tab. */
Search.setContent (new Intent(this, Search.class));
AllArtists.setContent (new Intent(this, AllArtists.class));
Favorites.setContent (new Intent(this, Favorites.class));
About.setContent (new Intent(this, About.class));
/** Add tabSpec to the TabHost to display. */
tabHost.addTab(Search);
tabHost.addTab(AllArtists);
tabHost.addTab(Favorites);
tabHost.addTab(About);
}
}
2) AllArtists (The Activity within the tab. Clicking a list item starts a new Activity):
public class AllArtists extends Activity {
// Debug
private final String TAG = this.getClass().getSimpleName();
// XML
EditText searchBox;
ListView listView;
// Adapter
ListAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allartists);
listAdapter = new ListAdapter(this, null);
// XML
listView = (ListView)findViewById(R.id.allartists_listview);
searchBox = (EditText)findViewById(R.id.allartists_searchbox);
listView.setAdapter(listAdapter);
listView.setFastScrollEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String memberID = (String)listAdapter.getID(position).toString();
if (!memberID.equals("HEADER")){
Log.d(TAG, "Jumping to Artists.class");
Intent intentArtist = new Intent (AllArtists.this, Artist.class);
intentArtist.putExtra("ID", memberID);
startActivity(intentArtist);
}
}
});
}
3) Artist (The new Activity started. This class does not register OnClick):
public class Artist extends Activity implements OnClickListener{
// Debug
private final String TAG = this.getClass().getSimpleName();
// XML
Button favorite_btn;
LinearLayout tel;
LinearLayout mob;
LinearLayout email;
LinearLayout www1;
LinearLayout www2;
LinearLayout add;
TextView name_tv;
TextView tel_tv;
TextView mob_tv;
TextView email_tv;
TextView www_tv1;
TextView www_tv2;
// Strings
String memberID;
String sirName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist);
Toast.makeText(this, "OK, your in Activity_Artist..", Toast.LENGTH_SHORT);
// XML
favorite_btn = (Button)findViewById(R.id.artist_ib_favorite);
tel = (LinearLayout)findViewById(R.id.artist_tel_container);
mob = (LinearLayout)findViewById(R.id.artist_mob_container);
email = (LinearLayout)findViewById(R.id.artist_email_container);
www1 = (LinearLayout)findViewById(R.id.artist_www_container1);
www2 = (LinearLayout)findViewById(R.id.artist_www_container2);
add = (LinearLayout)findViewById(R.id.artist_add_container);
name_tv = (TextView)findViewById(R.id.artist_tv_name);
tel_tv = (TextView)findViewById(R.id.artist_tel_dynamic);
mob_tv = (TextView)findViewById(R.id.artist_mob_dynamic);
email_tv = (TextView)findViewById(R.id.artist_email_dynamic);
www_tv1 = (TextView)findViewById(R.id.artist_www_dynamic1);
www_tv2 = (TextView)findViewById(R.id.artist_www_dynamic2);
// OnClickListeners
favorite_btn.setOnClickListener(this);
tel.setOnClickListener(this);
mob.setOnClickListener(this);
email.setOnClickListener(this);
www1.setOnClickListener(this);
www2.setOnClickListener(this);
add.setOnClickListener(this);
// Code here to get memberID for fillContent()
}
private void fillContent(String memberID) throws JSONException {
// Code here to fill the TextViews etc with content from the DataBase.
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.artist_ib_favorite:
Toast.makeText(this, "onClick", Toast.LENGTH_SHORT);
Log.d(TAG, "Neo is attempting to insert member into favorites");
MyDB db = new MyDB(this);
db.insertFavorite(memberID, sirName);
break;
case R.id.artist_tel_container:
break;
case R.id.artist_mob_container:
Log.d(TAG, "OMG CLICKED THE MOBILE!");
break;
case R.id.artist_email_container:
break;
case R.id.artist_www_container1:
break;
case R.id.artist_add_container:
break;
}
}
Thanks ;)
For Toast you need to call show.
Toast.makeText(this, "OK, your in Activity_Artist..", Toast.LENGTH_SHORT).show();
For the click Operation on anything apart from Button you need to define
android:clickable="true"
in the layout.
Solved this. In the layout there was an (empty) GridView at the bottom of the layout set to android:layout_height="fill_parent" wich stole the touchevent.
The weird part about this is that when putting the exact same activity with the exact same XML inside a tab, the onClick() worked fine.
I have a MapActivity as one of four tabs in a TabActivity. This MapActivity can launch a PopupWindow that is a legend. The PopupWindow remains on the screen, on top of the map, until the "Show Legend" button is clicked again (back and forth, etc.).
The problem is that, when a user switches to another tab, the PopupWindow remains persistent over the view.
I've tried implementing the onPause() method in the MapActivity class, and dismissing it from there. The application force closes with this method in place.
Any help? Thanks!
EDIT: Here's some of my code:
In the MainActivity, which establishes the four tabs:
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable 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, FirstActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("game").setIndicator("First",
res.getDrawable(R.drawable.ic_tab_game))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, SecondActivity.class);
spec = tabHost.newTabSpec("alerts").setIndicator("Second",
res.getDrawable(R.drawable.ic_tab_alert))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, MapActivity.class);
spec = tabHost.newTabSpec("map").setIndicator("Map",
res.getDrawable(R.drawable.ic_tab_map))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, LastActivity.class);
spec = tabHost.newTabSpec("experience").setIndicator("Last",
res.getDrawable(R.drawable.ic_tab_experience))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
Now in my MapActivity class (which extends MapActivity):
// Declare the Legend PopupWindow
mapLegendInflater = (LayoutInflater) MapActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mapLegendPopupLayout = mapLegendInflater.inflate(
R.layout.maptablegendpopuplayout, null, false);
mapLegendPopup = new PopupWindow(mapLegendPopupLayout,
(int) (0.45 * getApplicationContext().getResources()
.getDisplayMetrics().widthPixels),
(int) (0.33 * getApplicationContext().getResources()
.getDisplayMetrics().heightPixels), true);
mapLegendPopup.setFocusable(false);
mapLegendPopup.setOutsideTouchable(true);
Boolean legendIsShown = false;
mapLegendButton = (Button) findViewById(R.id.buttonMapLegend);
mapLegendButton.setOnClickListener(mapLegendListener);
private OnClickListener mapLegendListener = new OnClickListener() {
public void onClick(View v) {
// Launch or dismiss the map legend popup
if (legendIsShown) {
mapLegendPopup.dismiss();
mapLegendButton.getBackground().clearColorFilter();
legendIsShown = false;
} else {
mapLegendPopup.showAtLocation(
findViewById(R.id.buttonMapLegend), Gravity.TOP
| Gravity.LEFT, 8,
(int) (0.23 * getApplicationContext().getResources()
.getDisplayMetrics().heightPixels));
mapLegendButton.getBackground().setColorFilter(
new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));
// mapLegendButton.getBackground().setColorFilter(0xFFFFFF00,
// PorterDuff.Mode.MULTIPLY);
legendIsShown = true;
}
}
};
I hope this provides an idea of where I'm at. Everything works perfectly well on the Map tab. It's only when you have the Legend shown and switch tabs that it is still displayed on other views.
I know you said that implementing onPause() did not work for you, but I tried it and implementing onResume() and onPause() in the MapActivity does work for me.
I needed to do a View.post(new Runnable() { ... }) in onResume() since I could not recreate the popupWindow during the onResume() so I had to schedule it to occur immediately afterwards:
package com.esri.android.tabdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public class MapActivity extends Activity
{
private TextView textView = null;
private PopupWindow popupWindow = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setText("Hello World from MapActivity");
setContentView(textView);
}
#Override
protected void onPause()
{
super.onPause();
if (popupWindow != null)
{
popupWindow.dismiss();
popupWindow = null;
}
}
#Override
protected void onResume()
{
super.onResume();
final Context context = this;
textView.post(
new Runnable()
{
public void run()
{
popupWindow = new PopupWindow(context);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Button button = new Button(context);
button.setText("Hello");
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
});
linearLayout.addView(button);
popupWindow.setContentView(linearLayout);
popupWindow.showAtLocation(linearLayout, Gravity.LEFT | Gravity.BOTTOM, 10, 10);
popupWindow.update(256, 64);
}
}
);
}
}
You can init your popupwindown like this:
mapLegendPopup = new PopupWindow(this);
mapLegendPopup.setContentView (itemizeView);
mapLegendPopup.setBackgroundDrawable (new BitmapDrawable()); // key is here
mapLegendPopup.setWidth ((int) (0.45 * getApplicationContext().getResources()
.getDisplayMetrics().widthPixels));
mapLegendPopup.setHeight((int) (0.33 * getApplicationContext().getResources()
.getDisplayMetrics().heightPixels));
mapLegendPopup.setFocusable(false);
mapLegendPopup.setOutsideTouchable(true);
You should manage your Dialogs by using the onCreateDialog() method, as recommended by the framework.
That way your Dialog will become part of your Activity and it will do it by itself.
If you really don't want to use that (I can't see any reason why that would be the case, but still), you can use the setOwnerActivity() on your Dialog to assign it to your Activity.