开发者

npe when trying to add a view to tabhost with setId ids

trying to create a view based tabhost programmatically, but i get a fc from a npe as pasted below. i can find the views with findbyid. what am I missing? thanks.

  public class tabs_view extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TabHost th=new TabHost(this);

        Button b=new Button(this);
        b.setId(1001);
        b.setText("1");
        th.addView(b);

        TabHost.TabSpec ts=th.newTabSpec("1");
        ts.setIndicator("1");
        ts.setContent(1001); //nullpointer exception originates here (line 27)       
        th.addTab(ts);
        setContentView(th);
  /*
  RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
  E/AndroidRuntime(11234):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
  ...
  E/AndroidRuntime(11234): Caused by: java.lang.NullPointerException
  E/AndroidRuntime(11234):        at android.widge开发者_JAVA百科t.TabHost$ViewIdContentStrategy.<init>(TabHost.java:583)
  E/AndroidRuntime(11234):        at android.widget.TabHost$ViewIdContentStrategy.<init>(TabHost.java:578)
  E/AndroidRuntime(11234):        at android.widget.TabHost$TabSpec.setContent(TabHost.java:435)
  E/AndroidRuntime(11234):        tabs_view.onCreate(tabs_view.java:27)
  */
      }
  }


Rather than doing the extra work of finding the ID, have you tried just using the automatic resource mechanism? or maybe try pulling your tabs into a separate TabActivity from your main activity.

th.addTab(th.newTabSpec("1")
            .setIndicator("1")
            .setContent(R.id.view1));

There's always the API Demos code that you can look through: Tab sample code

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜