2013-05-04 68 views
1

我在使用findViewByID方法在片段中遇到问题。findViewById在片段中返回null

微调框Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location);始终为空。请参阅下面的代码。

public class FragmentTabSearch extends SherlockFragment implements OnItemSelectedListener { 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    View view = inflater.inflate(R.layout.fragment_tab_suggestions, container, false); 

    Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location); 
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getSherlockActivity(), R.array.spinner_location, android.R.layout.simple_spinner_item); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(adapter); 

    return view; 
} 

@Override 
public void onItemSelected(IcsAdapterView<?> parent, View view, 
     int position, long id) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onNothingSelected(IcsAdapterView<?> parent) { 
    // TODO Auto-generated method stub 

} 

}

布局文件是如下(PS:我已宣布在值/ ids.xml文件中的ID/tabsearchspinner_location):<item type="id" name="tabsearchspinner_location"></item>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<Spinner 
    android:id="@id/tabsearchspinner_location" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

<ListView 
    android:id="@id/tablistview_search" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
</ListView> 

任何帮助表示赞赏!

+0

你可以发布堆栈跟踪的例外吗? – Luksprog 2013-05-05 12:06:16

+0

我已经找到问题了,谢谢。 – UnkDrew 2013-05-05 13:37:19

回答

0

对不起,我刚刚发现我夸大了错误的布局,所以findViewById方法总是返回null,感谢所有的帮助。

2

虚增您View没有ViewGroup,因为它只是你的FragmentActivity内:

View view = inflater.inflate(R.layout.fragment_tab_suggestions, null); 

和ID在XML布局文件中添加的方式是这样的:

android:id="@+id/tabsearchspinner_location" 

,你可以看,你错过了+

+0

我已经在我已经删除的答案中用'+'指出了这件事,但后来我注意到他已经在不同的XML文件中定义了ID。 – zbr 2013-05-04 15:09:54

+0

你的答案中没有“膨胀”方法。 – Luksprog 2013-05-04 15:16:45

+0

谢谢,但我不能找到这样的'充气'的方法。我已经在xml文件中声明了id,所以我不会错过“+”。 – UnkDrew 2013-05-04 16:06:54