【问题标题】:Android - Fragment findViewById() always null?Android - 片段 findViewById() 总是为空?
【发布时间】:2014-12-23 10:32:53
【问题描述】:

是的,我意识到有些问题与这个问题非常相似,但与其他问题不同的是,我的 onCreateView() 方法会放大片段的视图。当我不使用 findViewById() 时,一切都会膨胀,我的应用程序会按预期工作(除了我想在 findViewById() 中获得的视图的功能。

这是我的代码:

@Override
public View onCreateView(LayoutInflater p_inflater, ViewGroup p_container, Bundle p_prev_state)
{
    return p_inflater.inflate(R.layout.fragment_main, p_container, false);
}

每当我想访问布局中的 ListView 时,我都会这样做:

private ListView getListView()
{
    return (ListView)getView().findViewById(R.id.main_events);
}

但这始终为空。为什么?我的fragment_main.xml 看起来像这样:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context="me.k.cal.MainActivity$PlaceholderFragment" >

    <ListView android:id="@+id/main_events"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="1dp"
        android:divider="@color/background_color" />

</RelativeLayout>

My full fragment code can be found here.

【问题讨论】:

  • findViewById 可以附加一个视图。所以在 Fragment 中,你需要使用它作为view.findViewById
  • 关于片段生命周期,您究竟何时调用getListView() 或调用它的方法?

标签: java android xml android-fragments


【解决方案1】:

使用下面的代码来扩充您的视图并获取列表视图的 id。

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {                                                                                                                                                                                                                                                           
    View _view = inflater.inflate(R.layout.fragment1, container, false);

    ListView _list= (ListView) _view.findViewById(R.id.main_events);
    return _view;
}

【讨论】:

  • 感谢您的回答并为我的缓慢响应时间道歉。当我运行这个时,_list 视图仍然为空... 是否调用了 onCreateView() 来代替 ctor?
  • 我认为您的布局在活动 xml 中,您正在从片段访问它。
【解决方案2】:

试试这个,希望对你有帮助

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }
    View view = inflater.inflate(R.layout.fragment_main, container,
            false);

    ListView eventsList= (ListView) view.findViewById(R.id.main_events);

 return view;

}

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2014-09-15
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多