【发布时间】:2017-09-11 12:54:18
【问题描述】:
我正在尝试从另一个 xml 文件 (fragment_friends.xml) 获取列表视图 ID,而我在 activity_main.xml 布局中。我尝试了 2 种方法,但它们都无法正常工作。
下面的代码将导致应用程序立即崩溃,因为我正在尝试获取此布局中不存在的 id (activity_main)
原始代码
ListView friendList = (ListView) findViewById(R.id.friend_listView);
friendList.setAdapter(friendAdaptor);
以下代码有效,但我无法将任何数据插入或显示到我的数据库中。
尝试 1 个代码:
View inflatedView = getLayoutInflater().inflate(R.layout.fragment_friend, null);
ListView friendList = (ListView) inflatedView.findViewById(R.id.friend_listView);
friendList.setAdapter(friendAdaptor);
下面的代码数据库和listView可以工作,但是我的导航栏抽屉不见了,当我尝试返回activity_main时,应用程序崩溃了
尝试 2 个代码
setContentView(R.layout.fragment_friend);
ListView friendList = (ListView) inflatedView.findViewById(R.id.friend_listView);
friendList.setAdapter(friendAdaptor);
app_bar_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!--<include layout="@layout/content_main" />-->
<FrameLayout
android:id="@+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
【问题讨论】:
-
我将删除我原来的答案并提供一个新答案,希望能解决这里发生的所有问题。
-
好的,我也更新了app_bar main的代码
标签: android listview layout-inflater findviewbyid setcontentview