Tab change listener android

后端 未结 6 1578
我寻月下人不归
我寻月下人不归 2021-01-07 16:22

My HomeActivity extends AppCompatActivity that uses 2 tabs.

public class HomeActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSection         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 17:09

    You should implement OnTabChangeListener to the TabActivity class rather than the contents of the Tab.

    In your TabActivity implement OnTabChangeListener

    then set the listener for the TabHost mTabHost.setOnTabChangedListener(this);

    Ex.1

    @Override
    public void onTabChanged(String tabId) {
        Log.i("selected tab ", tabId);
    
    }
    

    Ex.2

      public class HelloTabWidget extends TabActivity implements OnTabChangeListener{
    
    private TabHost mTabHost;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        Resources res = getResources(); 
        TabHost tabHost = getTabHost();  
        TabHost.TabSpec spec;  
        Intent intent; 
        mTabHost = getTabHost();
    
    
        intent = new Intent().setClass(this, BarActivity.class);
        spec = tabHost.newTabSpec("Name").setIndicator("Name",res.getDrawable(R.drawable.ic_tab_name)).setContent(intent);
        tabHost.addTab(spec);
    
        intent = new Intent().setClass(this, CityActivity.class);
        spec = tabHost.newTabSpec("city").setIndicator("City",res.getDrawable(R.drawable.ic_tab_city)).setContent(intent); 
        tabHost.addTab(spec);
    
        intent = new Intent().setClass(this, MapsActivity.class);
        spec = tabHost.newTabSpec("Country").setIndicator("Country",res.getDrawable(R.drawable.ic_tab_map)).setContent(intent);
        tabHost.addTab(spec);        
    
        tabHost.setCurrentTab(2);
        mTabHost.setOnTabChangedListener(this);
    }
    
    public void onTabChanged(String tabId) {
        Toast.makeText(getApplicationContext(), "Selected Tab "+tabId, Toast.LENGTH_LONG).show();
        Log.i("selected tab index", "Current index - "+ mTabHost.getCurrentTab());      
    }} 
    

提交回复
热议问题