【发布时间】:2019-09-10 07:39:24
【问题描述】:
我正在开发一个应用程序,我必须在片段上实现 onClick 方法。单击按钮时,我想打开另一个片段,但片段 ID 出现错误。
我在onClick 方法中使用了片段管理器和片段事务,如下所示:
override fun onClick(v: View?) {
val fm = childFragmentManager
val ft = fm.beginTransaction()
ft.add(R.layout.fragment_extended_subscribers, ExtendedSubscribersFragment())
ft.addToBackStack(null)
ft.commit()
我也尝试在 FrameLayout 中添加一个 id 并将其添加到片段事务中,但仍然是同样的错误:
ft.add(R.id.fragment_for_subs,ExtendedSubscribersFragment())
logcat 错误是:
java.lang.IllegalArgumentException: No view found for id 0x7f0d0037 (al.mgr.ekranet:layout/fragment_extended_subscribers) for fragment ExtendedSubscribersFragment{d6186df #0 id=0x7f0d0037}
这是我的onCreateView 函数:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_extended_subscribers, container, false)
getAllSubscribers()
return view
这是与片段关联的布局。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_for_subs"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".homeFragments.ExtendedSubscribersFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/all_subscribers_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
【问题讨论】:
-
An
R.layout是错误的,并且总是会抛出该异常。您需要为要放置Fragment的ViewGroup指定R.id,而不是Fragment自己的布局中的一个。 -
@MikeM。我也尝试过像这样使用 id:ft.add(R.id.fragment_for_subs,ExtendedSubscribersFragment()) 但仍然是同样的错误
-
是的,您在问题中提到了这一点。
fragment_for_subs在哪个布局中? -
您能发布您的
onCreateView功能吗?还有布局? -
"您需要为
ViewGroup指定R.id,而不是Fragment自己的布局中的R.id。"
标签: android kotlin fragmenttransaction