我注意到,在创建片段之后,需要一个元素。在Java中,只需要getActivity()
,但在Kotlin中似乎更加困难。 <
中的>
和mTwoPane = <FragmentActivity>(activity).findViewById(R.id.master_container) != null
带红色下划线并返回此错误:
期待元素
class MyFragment() : Fragment() {
private var mAdapter: MyListAdapter? = null
internal lateinit var mRecyclerView: RecyclerView
var mTwoPane: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.md, container, false)
mTwoPane = <FragmentActivity>(activity).findViewById(R.id.master_container) != null
mRecyclerView = view.findViewById(R.id.recyclerView_list)
mRecyclerView.setHasFixedSize(true)
mRecyclerView.layoutManager = LinearLayoutManager(this.activity)
mRecyclerView.addItemDecoration(DividerItemDecoration(Objects.requireNonNull<Context>(context), LinearLayout.VERTICAL))
val myList = ArrayList<Product>()
val items = resources.getStringArray(R.array.product_names)
val itemDescriptions = resources.getStringArray(R.array.product_descriptions)
for (n in items.indices) {
val product = Product(items[n], itemDescriptions[n])
myList.add(product)
}
mAdapter = MyListAdapter(activity, myList, mTwoPane)
mRecyclerView.adapter = mAdapter
return view
}
}
答案 0 :(得分:2)
尝试
mTwoPane = (activity as FragmentActivity).findViewById<View>(R.id.master_container) != null