Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass and get value from fragment and activity

How to pass and get value from fragment and activity?

like image 975
Best Best Avatar asked Oct 03 '17 18:10

Best Best


People also ask

How do you pass a value from activity to activity?

This example demonstrates how do I pass data between activities in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.


2 Answers

Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").

Put this in your Fragment:

class MyFragment: Fragment {  ...      companion object {              @JvmStatic             fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {                 arguments = Bundle().apply {                     putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)                 }             }      } } 

.apply is a nice trick to set data when an object is created, or as they state here:

Calls the specified function [block] with this value as its receiver and returns this value.

Then in your Activity or Fragment do:

val fragment = MyFragment.newInstance(false) ... // transaction stuff happening here 

and read the Arguments in your Fragment such as:

private var isMyBoolean = false  override fun onAttach(context: Context?) {     super.onAttach(context)     arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {         isMyBoolean = it     } } 

Enjoy the magic of Kotlin!

like image 192
Paul Spiesberger Avatar answered Sep 26 '22 02:09

Paul Spiesberger


There is the companion object for that (https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects )

Define your fragment as usual, and declare the companion that acts as the static newInstance() equivalent in Java :

class ViewStackListFragment : Fragment() {   companion object {         fun newInstance(position: Int): ViewStackListFragment {             val fragment = ViewStackListFragment()             val args = Bundle()             args.putInt("position", position)             fragment.setArguments(args)             return fragment         }     } } 

And simply call it like in Java :

val fragment = ViewStackListFragment.newInstance(4) 
like image 38
NSimon Avatar answered Sep 25 '22 02:09

NSimon