can anyone give sample code for TabHost in Android?

前端 未结 4 2004
春和景丽
春和景丽 2021-02-10 06:50

I need sample code to create TabHost in android. can anyone help me.

4条回答
  •  有刺的猬
    2021-02-10 07:30

    res/layout/activity_main.xml

    
    
    
    
        
    
            
    
            
    
                
    
                    
    
                
    
                
    
                    
                
    
                
    
                    
                
            
        
    
    

    src/MainActivity.java

      public class MainActivity extends AppCompatActivity {
    TabHost tabHost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        TabHost host = (TabHost)findViewById(R.id.tabHost);
        host.setup();
    
        //Tab 1
        TabHost.TabSpec spec = host.newTabSpec("Tab One");
        spec.setContent(R.id.tab1);
        spec.setIndicator("Tab One");
        host.addTab(spec);
    
        //Tab 2
        spec = host.newTabSpec("Tab Two");
        spec.setContent(R.id.tab2);
        spec.setIndicator("Tab Two");
        host.addTab(spec);
    
        //Tab 3
        spec = host.newTabSpec("Tab Three");
        spec.setContent(R.id.tab3);
        spec.setIndicator("Tab Three");
        host.addTab(spec);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    } 
    

    You can Follow these tutorials for help

    Creating a tabbed UI with TabHost

    Android Tab Layout Tutorial

提交回复
热议问题