Capturing click event on Android Tabview tab

I have a tab in my Android app with 3 tabs. All tabs work fine.

Now I want to perform additional logic when the tab (top) of the current active tab is clicked.

Here is an example:

In one of my tabs, I give the user the ability to sort things in a different order. When you click the tab of the currently active tab, I want to reset all of these sorts.

Is it possible to capture the click event of a tab and execute some additional logic?

Edit: Edited for clarity.

+6
android tabs
source share
4 answers

If you start looking for a solution, I may have found it. Take a look here: Android TabWidget will detect that click on the current tab

+3
source share

Here's how your code should work:

getTabWidget().getChildAt(getTabHost().getCurrentTab()).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //do whatever you need } }); 
+4
source share

I found one clean and simple solution for detecting clicks on a selected tab

Steps:

1: Extend TabActivity in your class. 2: In the onResume () method, we implement the following method

For each tab (i), do the following:

 TabHost tabHost = getTabHost(); public void onResume() { super.onResume(); tabHost.getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener() { public void onClick(View v) { count++; tabHost.setCurrentTab(0); //based on your count value..you can do anything...like going back to homepage... // similar thing exist on iphone (double tab a tab..it takes back to homepage) } }); } 

Since we always have a fixed number of tabs, implementing it individually is not a problem.

+3
source share
  for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) { getTabWidget().getChildAt(i).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (getTabHost().getCurrentTabTag().equals(v.getTag())) { int nextTab = getTabHost().getCurrentTab(); tabHost.setCurrentTab(prevTab); tabHost.setCurrentTab(nextTab); prevTab = nextTab; } else tabHost.setCurrentTabByTag((String) v.getTag()); } }); } 

You need a global variable;

  private int prevTab = 1; //any tab except the initial one. 

This code works for me. A bit ugly thing, you have to set the same tag for the tab and view For example:

  intent = new Intent().setClass(this, AnaSayfa.class); spec = tabHost.newTabSpec("firstTab").setIndicator(makeTabIndicator(R.drawable.firstTab, "First Tab" , "firstTab")) .setContent(intent); tabHost.addTab(spec); 

and the makeTabIndicator method is similar to this,

  private View makeTabIndicator(int drawable, String text, String viewTag){ View view = LayoutInflater.from(this).inflate(R.layout.tab_layout, null); ImageView image = (ImageView) view.findViewById(R.id.imageView1); image.setImageResource(drawable); image.setAdjustViewBounds(true); TextView tv = (TextView) view.findViewById(R.id.textView1); tv.setText(text); view.setTag(viewTag); return view; } 
0
source share

All Articles