In Android, how do I close TabWidget when a tab is selected?
I want close the TabWidget where some tab is selected.
//I use the OnTabChangeListener solve the question.
mTabHost.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
if (DEBUG) Log.d(TAG, "onTabChanged()");
if("testTabId".equals(tabId)) {
//destroy earth
Intent intentTabMe = new Intent(MainActivity.this, UserDetailsActivity.class);
intentTabMe.setAction(Intent.ACTION_VIEW);
startActivity(intentTabMe);
}
}
});
Related
how to show toast message for tab tiles, public String[] tab_titles = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; when on the individual tab
I am not sure that you can get tab name.but you may get TabSpec name.
try below code hope it will help you.
TabHost tabHost;
tabHost = (TabHost) rootView.findViewById(R.id.tab_host);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("Tabspec1").setIndicator("Academics").setContent(R.id.academicslistview));
tabHost.addTab(tabHost.newTabSpec("Tabspec2").setIndicator("Extracurricular").setContent(R.id.extracurricularlistview));
tabHost.setCurrentTab(0);
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
int selectedTab = tabHost.getCurrentTab();
Log.d("Tab", "count" + selectedTab);
Toast.makeText(getApplicationContext(), "Tab Title" + mTabHost.getCurrentTab(), Toast.LENGTH_LONG).show();
}
});
I have implemented a tab layout with swipeable views, it has 5 tabs.
in my 1st four tabs i have loaded grid menus. if i select one of those items in da grid it will open a new activity.
in my manifest.xml file i have used this line to navigate it back.
android:parentActivityName="xxxxxxx.ActivityMenuGrid"
when i select an item in my 2nd,3rd or 4th tabs and press the back navigation button on left top corner of my screen then it will go back to and open up and display the 1st tab, not the tab where i selected the required item.
but if i press the back button in my phone it will navigate me back to the tab where i open the new activity.
how can i navigate my back navigation in my left top corner to the appropriate tab.
public class ActivityMenuGrid extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
public TabHost myTabHost;
// Tab titles
private String[] tabs = { "", "", "", "", "" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_p));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_n));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_s));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_pr));
actionBar.addTab(actionBar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_tab_pro);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// set background for action bar tab
bar.setStackedBackgroundDrawable(new ColorDrawable(Color
.parseColor("#f8f8f8")));
bar.show();
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// getActionBar().setTitle(tab.getText());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
im selecting a item from tab2,
then it will openup new activity. and it has back navigation button.
when i press the back navigation button then it will go back to the tab1, not tab 2. I want to fix that issue and navigate it to tab2.
FYI- when i press the back navigation hardware button in the phone it will navigate it to tab 2.
any help will be highly appreciated.
you have to override the activitys onBackPresed function and have to write the logic to to move to the'desired tab. doing this will prevent your app from close(default navigation on back button pressed) with android hardware back button, also you have to check if you are in desired tab already and pass the event super.onBackPressed(); to the OS to close the app or handle tha default navigation.
The below code states when you press back button it is starting new activity and you are not overriding that.Check once with that.
#Override - > Missing.
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
I would suggest one edit
Try to set position of the tab in onPageSelected method and when back pressed check the previous position where it exactly and navigate to it.
Ex :
static int pos =0;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
pos=position;
}
#Override
public void onBackPressed() {
try {
switch (pos) {
case 0: // Means Main Activity : Do Default action
super.onBackPressed();
break;
case 1:
case 2:
case 3://Other than main tab open previous positioned tab.
viewPager.setCurrentItem(pos, true);
break;
}
} catch (Exception e) {
super.onBackPressed();
}
}
I had same problem and it worked for me.Glad if i could help you.
I was able to achive it by doing,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I have these codes for my two tabs. I would like to change the color but I dont know how to do it. Should it be done in my java file, or in my xml ? Thank You
Here are my codes
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TabHost;
// This is now the first activity that you see when you enter the app, it derives from TabActivity
public class TabsActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// The activity displays a TabHost layout with a TabWidget below the actual tab contents
setContentView(R.layout.tabs);
// Two tabs are added one displays the main list activity, the other an info activity
addNewTab("Kalender", MainActivity.class);
addNewTab("Info", InfoActivity.class);
}
// This function defines and adds a tab to the interface
private void addNewTab(String name, Class<? extends Activity> activityClass)
{
TabHost tabHost = getTabHost();
// The new tab will display a separate activity, so it needs an intent for it
Intent activityIntent = new Intent().setClass(this, activityClass);
// The TabSpec sets the internal name and the visible name of the newly created tab
TabHost.TabSpec spec = tabHost.newTabSpec(name).setIndicator(name).setContent(activityIntent);
// Finally, the new tab is added to the TabHost
tabHost.addTab(spec);
}
}
Changing text Color and Background color of TAB
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE); //Changing background color of tab
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); /*for Selected Tab changing text color*/
tv.setTextColor(Color.BLACK);
}
This is one way to make the background of a single tab have a color, and also to set one.
tabHost.getTabWidget().getChildAt(tabIndex).setBackgroundColor(color);
If you want to customize the look of your tabs, you should use your own tab widget. The thing is that most android widgets are themed using bitmaps, so you can't simply change the gradient color.
Some people suggest simply changing the backgroundColor of the standard widget, but it is going to look rather flat.
Using your own widget goes something like this:
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
Also have a look at the Android style guide's tab section.
Hey if you want to change the tab color just like in Google Playstore try this:
public class MainActivity extends AppCompatActivity implements TabLayout.BaseOnTabSelectedListener {
private AppBarLayout appBarLayout;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private View mRevealView;
private View mRevealBackgroundView;
private int fromColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appBarLayout = findViewById(R.id.main_appbar);
toolbar = findViewById(R.id.main_toolbar);
tabLayout = findViewById(R.id.main_tablayout);
viewPager = findViewById(R.id.main_viewPager);
mRevealView = findViewById(R.id.reveal);
mRevealBackgroundView = findViewById(R.id.revealBackground);
setUpTabs();
setSupportActionBar(toolbar);
fromColor = R.color.colorTabOne;
}
private void setUpTabs() {
viewPager.setAdapter(new ViewPagerAdapter());
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(this);
tabLayout.getTabAt(0).setText("TAB ONE");
tabLayout.getTabAt(1).setText("TAB TWO");
tabLayout.getTabAt(2).setText("TAB THREE");
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
animateAppAndStatusBar(0, R.color.colorTabOne);
break;
case 1:
animateAppAndStatusBar(appBarLayout.getWidth() / 2, R.color.colorTabTwo);
break;
case 2:
animateAppAndStatusBar(appBarLayout.getWidth(), R.color.colorTabThree);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
private void animateAppAndStatusBar(int cx, final int toColor) {
Animator animator = ViewAnimationUtils.createCircularReveal(
mRevealView,
cx,
appBarLayout.getBottom(), 0,
appBarLayout.getWidth() / 2);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
mRevealView.setBackgroundColor(getResources().getColor(toColor));
}
});
mRevealBackgroundView.setBackgroundColor(getResources().getColor(fromColor));
animator.setStartDelay(200);
animator.setDuration(125);
animator.start();
mRevealView.setVisibility(View.VISIBLE);
fromColor = toColor;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
ViewPagerAdapter() {
super(MainActivity.this.getSupportFragmentManager());
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new TabOneFragment();
case 1:
return new TabTwoFragment();
case 2:
return new TabThreeFragment();
default:
throw new IllegalArgumentException("Invalid position " + i);
}
}
#Override
public int getCount() {
return 3;
}
}
}
You can check out my Github or Youtube tutorial
I have created tab app.. now I am playing with screen rotation. I tried to set tabHost.getTabWidget().setCurrentTab(1), which should show second tab (first is 0). The point is that second tab is shown as selected, but shown content is from first tab... How can I solve that?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
myCommunicator = new Communicator();
dbAdapter = new ToDoDBAdapter(this);
if (getLastNonConfigurationInstance() != null)
{
CurrentTab = (Integer)getLastNonConfigurationInstance();
createView();
}
else
{
BuildDialog = ProgressDialog.show(this, "Loading", "Updating data...", true, false);
BuildDialog.show();
new LoadChannels().execute();
}
}
private void createView()
{
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
Intent intent;
TabSpec spec;
intent = new Intent().setClass(this, Channels.class);
// TAB 1
spec = tabHost.newTabSpec("kanali").setIndicator("Kanali",getResources().getDrawable(R.drawable.menu_channels)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Currently.class);
// TAB 2
spec = tabHost.newTabSpec("trenutno").setIndicator("Trenutno",getResources().getDrawable(R.drawable.menu_current)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Reminders.class);
// TAB 3
spec = tabHost.newTabSpec("opomniki").setIndicator("Opomniki",getResources().getDrawable(R.drawable.menu_reminder)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, About.class);
// TAB 4
spec = tabHost.newTabSpec("oprogramu").setIndicator("O programu",getResources().getDrawable(R.drawable.menu_about)).setContent(intent);
tabHost.addTab(spec);
tabHost.setBackgroundColor(Color.WHITE);
tabHost.setCurrentTab(1); // Should always set content to second
}
#Override
public Object onRetainNonConfigurationInstance()
{
return CurrentTab;
}
#Override
public void onTabChanged(String tabId) {
CurrentTab = tabHost.getCurrentTab();
}
public void onDestroy() {
super.onDestroy();
// Close the database
try {
dbAdapter.close();
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
createView();
}
Why are you calling getTabWidget()? You should use the setCurrentTab() on the tabHost itself.
Works fine here.
tabHost.setCurrentTab(1);
Use setCurrentTabByTag(String tag); Depending upon the tag you mentioned would be the default tab, hope it helps, works (It's currectly working for this code!!)
private static final String A ="Kanali"; //required defualt tab name
.
.
.
tabHost.setCurrentTabByTag (A);
link
Did you check TabHost in the debugger to be sure that all of the tabs were successfully added before you tried to set the currentTab? I had a similar issue and found that TabHost.setCurrentTab remains set to -1 if you try to reference an index that is outside of the range of tabs that were not successfully added. This behavior is not documented in the Android documentation.
I have three tabs and each one is its own activity. When I switch tabs I want my Spinner to update but I don't know what method gets called on tab switch. Any help?
Hook up a listener to the TabHost.OnTabChangeListener. You main activity extends TabActivity and its onCreate method probably looks something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
LayoutInflater.from(this).inflate(R.layout.tabs1, tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("tab1")
.setContent(R.id.view1));
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("tab2")
.setContent(R.id.view2));
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("tab3")
.setContent(R.id.view3));
}
To hook up the listener, add the following code in your onCreate() method:
tabHostt.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
if(tabId.equals("tab1")) {
//tab1
}
else if(tabId.equals("tab2")) {
//tab2
}
else if(tabId.equals("tab3")) {
//tab3
}
}
});
HTH
Something like this should work:
tabHost.setOnTabChangedListener(new OnTabChangeListener()
{
public void onTabChanged(String tabId)
{
//Do stuff in here
}
});