Why do I get an error while trying to set the content of a tabspec in android?

前端 未结 3 939
暗喜
暗喜 2020-12-18 07:37

I have an android activity in which I\'m using tabs.

public class UnitActivity extends TabActivity {
  @Override
  public void onCreate(Bundle savedInstanceS         


        
相关标签:
3条回答
  • 2020-12-18 07:47

    You also have to use LayoutInflater after TabHost

    LayoutInflater.from(this).inflate(R.layout.unit_data, tabHost.getTabContentView(), true);

    I also got stuck with this and finally figure it out.

    0 讨论(0)
  • 2020-12-18 07:48

    If you have your tab layout in a different file, you have to inflate the XML.

    spec = tabHost.newTabSpec("data");
    spec.setIndicator("Data");
    // Add the layout to your tab view
    getLayoutInflater().inflate(R.layout.unit_data, tabHost.getTabContentView(), true);
    spec.setContent(R.id.unit_data);   
    tabHost.addTab(spec);
    
    0 讨论(0)
  • 2020-12-18 08:02

    While Activity.setContentView takes an id of a Layout, TabSpec.setContent takes an id of a View. This means you need to pass an id that looks like R.id.something and not R.layout.something.

    To solve your particular problem, give the top level view in your layout a view id:

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:id="@+id/unit_data">  <!-- NOTE THE CHANGE -->
      ...
    </ScrollView>
    

    and update your source:

    public class UnitActivity extends TabActivity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.unit_view);
    
        TabHost tabHost = getTabHost();
        TabSpec spec;
    
        spec = tabHost.newTabSpec("controls");
        spec.setIndicator("Control");
        spec.setContent(R.id.unit_control);  // NOTE THE CHANGE
        tabHost.addTab(spec);
    
        spec = tabHost.newTabSpec("data");
        spec.setIndicator("Data");
        spec.setContent(R.id.unit_data);   // NOTE THE CHANGE
        tabHost.addTab(spec);
      }
    }
    

    For more information, see the tab examples in the ApiDemos:

    0 讨论(0)
提交回复
热议问题