Thou concept wise the above answer (https://stackoverflow.com/a/44469679/3845798) is correct, but there it needs to be in Kotlin. Like getActivity()
, getView()
will be access like a property.
Also, its val
not Val
.
Here is simple example of how to use findViewById()
, getSharedPreferences()
inside the activity.
MainActivity Code -
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setBaseFragment()
}
private fun setBaseFragment() {
val fragment = MainFragment.newInstance()
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
}
}
And this is my fragment Class
class MainFragment : Fragment() {
lateinit var show: Button
lateinit var save: Button
lateinit var text: TextView
var prefs: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_main, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
show = view?.findViewById(R.id.showButton) as Button
save = view?.findViewById(R.id.saveButton) as Button
text = view?.findViewById(R.id.textResult) as TextView
prefs = activity.getSharedPreferences("FUN",MODE_PRIVATE)
save.setOnClickListener {
val editor = prefs!!.edit()
editor.putString("Saving", "This is saveValueFromSharedPref")
editor.apply()
}
show.setOnClickListener {
text.setText(prefs?.getString("Saving","NotSaved"))
}
}
companion object {
fun newInstance(): MainFragment {
val fragment = MainFragment()
return fragment
}
}
}
It's a simple example with a text and two button.
First you have to save and show.
Also, for your app crash you can check this solution.