findViewById在新的Intent中返回null

问题描述:

我遇到了一个问题,在启动的Intent中,findViewById返回null。findViewById在新的Intent中返回null

有什么特别的我应该知道开始一个新的意图?

它是这样对我说:

//in the MainList class 
Intent stuffList = new Intent(this, StuffList.class); 

然后在新的东西的构造函数:

public class StuffList extends ListActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      this.setContentView(R.layout.stuff_list); 
      ... 
      this.setListAdapter(new StuffAdapter(this, my_cursor)); 

,并在StuffAdapter我做我通常的看法和数据检索。

记下findViewById返回null行:

class ViewWrapper{ 
    View base; 
    TextView label = null; 

    ViewWrapper(View base){ 
     this.base = base; } 

    TextView getLabel(){ 
     if(label == null){ 
      label = (TextView)base.findViewById(R.id.my_label); // returns NULL 
     } 
     return label;}  
} 

class StuffAdapter extends CursorAdapter{ 
     StuffAdapter(Context context, Cursor cursor){ 
      super(context, cursor); 
     }  

     @Override 
     public View newView(Context context, Cursor cursor, ViewGroup parent) { 
       LayoutInflater inflater = getLayoutInflater(); 
       View row = inflater.inflate(R.layout.stuff_list, parent, false); 
       ViewWrapper wrapper = new ViewWrapper(row); 

       row.setTag(wrapper); 
       return(row); 
     }  

     @Override 
     public void bindView(View row, Context context, Cursor cursor) { 
       ViewWrapper wrapper = (ViewWrapper)row.getTag(); 
       TextView label = wrapper.getLabel(); // also NULL 
       //this throws exception of course 
       label.setText(cursor.getString("title"));   
     } 
} 

好奇的是,在调用意图(MainList类)类的,我做同样的事情(我列出了一堆的对象)它的工作原理!然而,当我尝试以Intent执行它时,它似乎无法通过id找到视图。

为了完整,我想补充一点,我的列表资源文件叫做“stuff_list.xml”,我的行布局文件叫做“stuff_row.xml”。

+0

人,这个错误我发疯... – drozzy 2010-06-17 13:02:30

好的,这一课是 - 不要复制和粘贴你的代码。 这个问题正是在newView函数中,我试图膨胀一个列表而不是一行!

View row = inflater.inflate(R.layout.stuff_list, parent, false); 

,但它应该是:

View row = inflater.inflate(R.layout.stuff_row, parent, false); 

您可能为您的Main和StuffList活动使用了不同的内容视图(由于您未发布主活动的setContentView行,因此无法判断)。 你确定元素R.id.my_label实际上是在R.layout.stuff_list的xml中吗?可能不会。

+0

谢谢你接近。它应该是stuff_row! – drozzy 2010-06-17 13:08:07