我通过共享偏好从活动中获取片段中的数据,但无法执行该任务。
class ProfileFragment : Fragment() {
lateinit var sharedPreference: SharedPreferences
lateinit var txtName:TextView
lateinit var txtEmail:TextView
lateinit var txtMobileNo:TextView
lateinit var txtAddress:TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_profile, container, false)
sharedPreference = this.requireActivity().getSharedPreferences(getString(R.string.preference_file_name), Context .MODE_PRIVATE)
txtName = view.findViewById(R.id.title)
txtEmail = view.findViewById(R.id.Semail)
txtMobileNo = view.findViewById(R.id.Smobile)
txtAddress = view.findViewById(R.id.Sadress)
txtName.setText(sharedPreference.getString("title", "default")).toString()
txtName.setText(sharedPreference.getString("Email", "default")).toString()
txtName.setText(sharedPreference.getString("Mobile", "default")).toString()
txtName.setText(sharedPreference.getString("delivery", "default")).toString()
return view
}
}
您可以使用参数和可序列化数据:
data class UserDataUI(
val title: String,
val email: String,
val mobile: String,
val delivery: String
) : Serializable
在你的片段中:
companion object {
private const val ARG_USER_DATA_UI = "ARG_USER_DATA_UI"
fun newInstance(userDataUI: UserDataUI): ProfileFragment {
val bundle = Bundle().apply {
putSerializable(ARG_USER_DATA_UI, userDataUI)
}
return ProfileFragment().apply {
arguments = bundle
}
}
}
您需要调用ActivityProfileFragment.newInstance(yourData(来获取Fragment。
并将数据提取到片段中:
arguments!!.getSerializable(ARG_USER_DATA_UI) as UserDataUI
使用!!如果数据是强制性的,在这种情况下,永远不会为空
试着这样做
@Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences preferences = context.getSharedPreferences(getString(R.string.preference_file_name),Context .MODE_PRIVATE );
}
当您使用requireActivity()
时,如果片段没有附加到活动,它可以给出一个异常。