使用TabHost活动查找ViewById

时间:2012-08-20 19:36:42

标签: android android-layout

我是Android编码的新手,所以我希望有人可以帮助我.. 我发现了。有一个类似的问题how do I findviewbyid of a view inside a tabhost from an activity thats inside the tabhost? 但答案对我不起作用...我的应用程序包含一个main.xml和tab1.xml以及tab2.xml 每个人在这里都有一个Activity类代码:

public class MainActivity extends TabActivity {  


/** Called when the activity is first created. */ 
Intent tab1, tab2;

@Override 
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  

    TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);  


    TabSpec firstTabSpec = tabHost.newTabSpec("tid1");  
    TabSpec secondTabSpec = tabHost.newTabSpec("tid2");  

    tab1 = new Intent(this, tab1Activity.class);
    tab2 = new Intent(this, tab2Activity.class);

    firstTabSpec.setIndicator("TAB1").setContent(tab1);  
    secondTabSpec.setIndicator("Tab2").setContent(tab2);  

    tabHost.addTab(firstTabSpec);  
    tabHost.addTab(secondTabSpec);  

}

这里是tabHost的活动

  public class tab1Activity extends Activity
  {

/** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.xml);

    EditText t = (EditText) findViewById(R.id.note);
    t.setText("Test"); // here it crashes!

}

 }

所以我的问题是如何使用findViewById全局?我应该用意图吗? 如果有人帮助我会很棒!! : - )

1 个答案:

答案 0 :(得分:0)

我认为你应该检查你在contentView中设置的布局。可能是你问题的根源。

 public class tab1Activity extends Activity
  {

/** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.xml); // <-------- your problem could be here

    EditText t = (EditText) findViewById(R.id.note);
    t.setText("Test"); // here it crashes!

}

 }