我想将一些数据从PowerofMind传递到愿望清单片段,但是遇到一些错误。
此活动必须从其传输数据的地方
<p>1. The Sun
<select id="demo">
<option value="shine">shine</option>
<option value="shining">shining</option>
<option value="shines">shines</option>
</select>
</p><button onclick="myFunction()">Check!</button>
我希望在此活动中将数据显示为
wish?.setOnClickListener({
val name = "Power of Subconcoius Mind"
val intent = Intent(this@PowerofMind, WishlistFragment::class.java)
intent.putExtra("Book: ", name)
startActivity(intent)
Toast.makeText(this, "Added to WishList", Toast.LENGTH_SHORT).show()
})
但是Intent出错。请帮助
答案 0 :(得分:1)
这是一个如何使用工厂方法实例化片段的示例:
companion object {
private const val MY_DATA_KEY = "my_data"
private const val ANOTHER_DATA_KEY = "another_data"
fun newInstance(mySerializableData: Any, anotherData: Int) = MyFragment().apply {
//bundleOf() is an exstension method from KTX https://developer.android.com/kotlin/ktx
arguments = bundleOf(MY_DATA_KEY to mySerializableData, ANOTHER_DATA_KEY to anotherData)
}
}
答案 1 :(得分:0)
以下是使用Parcelable类在kotlin中的片段之间传递数据的方法:
在按钮上单击:
override fun onClick(v: View?) {
firstName = editTextName!!.text.toString()
lastName = editTextLast!!.text.toString()
Toast.makeText(context, firstName, Toast.LENGTH_SHORT).show()
// val viewFragment = ViewFragment()
// val transaction = fragmentManager.beginTransaction()
// transaction.replace(R.id.fragmentContainer, viewFragment)
// transaction.commit()
var details = Details(firstName!!, lastName!!)
val viewFragment = ViewFragment()
val bundle = Bundle()
bundle.putParcelable(KEY_PARSE_DATA, details)
viewFragment.setArguments(bundle)
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.fragmentContainer, viewFragment)
transaction.commit()
}
这是一个包裹类,如何处理数据
@Parcelize
class Details(val firstName: String, val lastName: String) : Parcelable
在另一个片段上
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_view, container, false)
textViewName = view.findViewById(R.id.text_name_another) as TextView
textViewLastName = view.findViewById(R.id.text_surname_another) as TextView
val bundle = arguments
if (bundle != null) {
val details = bundle.getParcelable<Details>(KEY_PARSE_DATA)
textViewName!!.setText(details.firstName)
textViewLastName!!.setText(details.lastName)
}
return view
}
目前,我不知道应用程序gradle中的kotlin是否需要此操作(使用前请先检查)
androidExtensions {
experimental = true
}
答案 2 :(得分:0)
在您的WishlistFragment中,您正在创建一个新的Intent,而不是获得活动提供的Intent。
使用Kotlin时,可以直接使用intent代替getIntent()。 您还可以利用kotlin的综合优势,并删除findViewById。
作为提示,请勿使用字符串串联;)
您的片段如下所示:
class WishlistFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_wishlist, null)
val name = activity?.intent?.getStringExtra("Book: ")
many.text = "Book: $name"
}