findViewById 在片段中返回 null [英] findViewById returns null in fragment

查看:41
本文介绍了findViewById 在片段中返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problem using the findViewByID methond in a fragment.

Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location); 中的微调器始终为空.请看下面的代码.

The spinner in Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location); is always null. Please see the code below.

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>

The layout file is as below (ps: I have already declared the id/tabsearchspinner_location in the values/ids.xml file): <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>

感谢任何帮助!

推荐答案

抱歉,我刚刚发现我膨胀了错误的布局,所以 findViewById 方法总是返回 null,谢谢大家的帮助不过.

Sorry, I just found out that I inflated the wrong layout, so the findViewById method always returns null, thanks for all the help though.

这篇关于findViewById 在片段中返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆