gpt4 book ai didi

java - Android - fragment findViewById() 始终为空?

转载 作者:行者123 更新时间:2023-12-01 18:24:35 27 4
gpt4 key购买 nike

是的,我意识到有些问题与此问题非常相似,但与其他问题不同,我的 onCreateView() 方法会膨胀 fragment 的 View 。当我不使用 findViewById() 时,一切都会膨胀,并且我的应用程序会按预期工作(除了我想要在 findViewById() 中获取的 View 的功能。

这是我的代码:

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

最佳答案

使用下面的代码来扩充您的 View 并获取 ListView 的 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;
}

关于java - Android - fragment findViewById() 始终为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com