【问题标题】:findViewById returns null in fragmentfindViewById 在片段中返回 null
【发布时间】:2013-05-04 14:44:05
【问题描述】:

我在片段中使用 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):&lt;item type="id" name="tabsearchspinner_location"&gt;&lt;/item&gt;

<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>

感谢任何帮助!

【问题讨论】:

  • 你能发布异常的堆栈跟踪吗?
  • 我已经找到了问题所在,谢谢。

标签: android android-fragments android-spinner findviewbyid


【解决方案1】:

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

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

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

android:id="@+id/tabsearchspinner_location"

如您所见,您缺少+

【讨论】:

  • 我已经在我已经删除的答案中指出了+ 的问题,但后来我注意到他已经在不同的 XML 文件中定义了 ID。
  • 您的答案中没有inflate 方法。
  • 谢谢,但我找不到这样的inflate 方法。而且我已经在xml文件中声明了id,所以我没有错过“+”。
  • 我记错了inflate方法,第二个参数应该是null
  • 对不起,微调器仍然为空。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2021-11-23
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多