findViewById在片段中返回null

时间:2013-05-04 14:44:06

标签: android android-fragments android-spinner findviewbyid

我在片段中使用findViewByID方法时遇到问题。

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:我已经在values / 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>

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

在没有View的情况下给ViewGroup充气,因为它只是在FragmentActivity中:

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

在XML布局文件中添加ID的方式如下:

android:id="@+id/tabsearchspinner_location"

正如您所看到的,您错过了+

答案 1 :(得分:0)

很抱歉,我发现我冒了错误的布局,所以findViewById方法总是返回null,感谢所有的帮助。