Search code examples
javaandroidandroid-tabhost

How do I programmatically create a Tab with EditText in it?


My app's text editor lets a user open and edit files, I want to open the file as a new tab in the TabHost so multiple files can be open. How do I add an EditText to a newly created Tab? This is what I tried in my onCreate()

TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
        tabHost.setup();
        EditText editor = new EditText(this);
        TabSpec spec1=tabHost.newTabSpec("Tab 1");
        spec1.setContent(editor.getId());
        spec1.setIndicator("Tab 1");

I assume the problem is `spec1.setContent(editor.getId());


Solution

  • You try to set an id (which was not defined by the way) as a layout id. It won't work that way. Try:

    TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
            tabHost.setup();
            EditText editor = new EditText(this);
            TabSpec spec1=tabHost.newTabSpec("Tab 1");
            spec1.setIndicator(editor); 
    

    if this is what you want. You can also try:

    TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
                tabHost.setup();
                final EditText editor = new EditText(this);
                TabSpec spec1=tabHost.newTabSpec("Tab 1");
                spec1.setContent(new TabHost.TabContentFactory(){
                     public View createTabContent(String tag){
                         return editor;
                     }
                 });